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.delete(np.where(A>0, A, 0).sum(axis=1))

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


>Solution :

An easy option is to repair the diagonal:

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

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


[[ 1 -2  0]
 [ 0  2  0]
 [-7  0 -2]]

Leave a Reply