来自 Getting indices of both zero and nonzero elements in array ,我可以像这样在 numpy 的一维数组中获取非零元素的索引:
indices_nonzero = numpy.arange(len(array))[~bindices_zero]
有没有办法把它扩展成二维数组?
请您参考如下方法:
你可以使用numpy.nonzero
下面的代码是不言自明的
import numpy as np
A = np.array([[1, 0, 1],
[0, 5, 1],
[3, 0, 0]])
nonzero = np.nonzero(A)
# Returns a tuple of (nonzero_row_index, nonzero_col_index)
# That is (array([0, 0, 1, 1, 2]), array([0, 2, 1, 2, 0]))
nonzero_row = nonzero[0]
nonzero_col = nonzero[1]
for row, col in zip(nonzero_row, nonzero_col):
print("A[{}, {}] = {}".format(row, col, A[row, col]))
"""
A[0, 0] = 1
A[0, 2] = 1
A[1, 1] = 5
A[1, 2] = 1
A[2, 0] = 3
"""
你甚至可以这样做
A[nonzero] = -100
print(A)
"""
[[-100 0 -100]
[ 0 -100 -100]
[-100 0 0]]
"""
其他变化
np.where(数组)
它等价于np.nonzero(array) 但是,np.nonzero 是首选,因为它的名字很清楚
np.argwhere(数组)
它等价于np.transpose(np.nonzero(array))
print(np.argwhere(A))
"""
[[0 0]
[0 2]
[1 1]
[1 2]
[2 0]]
"""
