获取二维数组非零元素的索引

use*_*827 1 python numpy

通过获取 array 中零和非零元素的索引,我可以像这样在 numpy 中获得一维数组中非零元素的索引:

indices_nonzero = numpy.arange(len(array))[~bindices_zero]

有没有办法将它扩展到二维数组?

Mo *_*o K 6

您可以使用 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
"""
Run Code Online (Sandbox Code Playgroud)

你甚至可以这样做

A[nonzero] = -100
print(A)
"""
[[-100    0 -100]
 [   0 -100 -100]
 [-100    0    0]]
 """
Run Code Online (Sandbox Code Playgroud)

其他变体

np.where(array)

它相当于np.nonzero(array) 但是,np.nonzero是首选,因为它的名字很清楚

np.argwhere(array)

它相当于 np.transpose(np.nonzero(array))

print(np.argwhere(A))
"""
[[0 0]
 [0 2]
 [1 1]
 [1 2]
 [2 0]]
 """
Run Code Online (Sandbox Code Playgroud)

  • 您应该扩展您的答案,解释它的作用以及它使用的“numpy”函数。 (2认同)
  • `np.nonzero`,或者它的别名 `np.where` 几乎不需要特别解释。 (2认同)