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...
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.