Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete positive elements of each row except diagonal elements in Python

I have an array A. I want to delete all positive elements of a row and replace it with zero but not the diagonal elements. But I am getting an error. I present the expected output.

import numpy as np
A=np.array([[1,-2,3],[1,2,6],[-7,8,-2]])
A=np.delete(np.where(A>0, A, 0).sum(axis=1))
print(A)

The error is

in <module>
    A=np.delete(np.where(A>0, A, 0).sum(axis=1))

  File "<__array_function__ internals>", line 4, in delete

TypeError: _delete_dispatcher() missing 1 required positional argument: 'obj'

The expected output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array([[1,-2,0],[0,2,0],[-7,0,-2]])

>Solution :

An easy option is to repair the diagonal:

B = np.where(A>0, A, 0)
np.fill_diagonal(B, A.diagonal())
print(B)

Note that this creates a new array, while the second approach below modifies A in place.

Another approach might be to get the x/y indices of the 2D array for which the value is 0 and only keep those not on the diagonal (x!=y):

x, y = np.where(A>0)
m = x!=y
A[x[m], y[m]] = 0

Output:

[[ 1 -2  0]
 [ 0  2  0]
 [-7  0 -2]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading