获取2D数组的非零元素的索引
问题描述:
从>获取零和非零元素的索引在数组中,我可以像这样在numpy中获得一维数组中非零元素的索引:
From Getting indices of both zero and nonzero elements in array, I can get indicies of non-zero elements in a 1 D array in numpy like this:
indices_nonzero = numpy.arange(len(array))[~bindices_zero]
有没有办法将其扩展到2D数组?
Is there a way to extend it to a 2D array?
答
您可以使用
You can use
您可以使用numpy.nonzero
以下代码不言自明
You can use numpy.nonzero
The following code is self-explanatory
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(array)
等效于np.nonzero(array)
但是,np.nonzero
是首选,因为它的名称很清楚
Other variations
np.where(array)
It is equivalent to np.nonzero(array)
But, np.nonzero
is preferred because its name is clear
等效于np.transpose(np.nonzero(array))
print(np.argwhere(A))
"""
[[0 0]
[0 2]
[1 1]
[1 2]
[2 0]]
"""