2

I have a numpy ndarray as follows"

x = np.array([[1, 2, 3], [4, 5, 6],[4, 1, 6],[1, 5, 11],[4,3, 4]], np.int32)

i set the value to zero if index with same col, row

rows = x.shape[0]
cols = x.shape[1]
for k in range(0, rows):
    for y in range(0, cols):
        if k==y:
            x[k,y]=0

expected output:

array([[ 0,  2,  3],
       [ 4,  0,  6],
       [ 4,  1,  0],
       [ 1,  5, 11],
       [ 4,  3,  4]])

Is there any simple (pythonic way to achieve the same results)? my actual matrix is very large...

1 Answer 1

3

Use np.fill_diagonal:

x = np.array([[1, 2, 3], [4, 5, 6],[4, 1, 6],[1, 5, 11],[4,3, 4]], np.int32)
np.fill_diagonal(x,0)

print(x)
array([[ 0,  2,  3],
       [ 4,  0,  6],
       [ 4,  1,  0],
       [ 1,  5, 11],
       [ 4,  3,  4]], dtype=int32)
Sign up to request clarification or add additional context in comments.

1 Comment

i wasnt aware fill_diagonal may apply to non-symmetric matrix. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.