获得2D阵列的非零元素的指示

时间:2017-05-21 03:24:00

标签: python numpy

Getting indices of both zero and nonzero elements in array开始,我可以在numpy的1 D数组中得到非零元素的指示,如下所示:

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

有没有办法将它扩展到2D数组?

2 个答案:

答案 0 :(得分:4)

您可以使用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(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]]
 """

答案 1 :(得分:0)

A = np.array([[1, 0, 1],
              [0, 5, 1],
              [3, 0, 0]])

np.stack(np.nonzero(A), axis=-1)

array([[0, 0],
       [0, 2],
       [1, 1],
       [1, 2],
       [2, 0]])

np.nonzero返回一个数组元组,每个数组对应a的一个维,其中包含该维中非零元素的索引。

https://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html

np.stack沿着新轴连接该元组数组。在我们的示例中,最里面的轴也称为最后一个轴(用-1表示)。

axis参数指定结果范围内新轴的索引。例如,如果axis = 0,它将是第一个尺寸;如果axis = -1,它将是最后的尺寸。

1.10.0版中的新功能。

https://docs.scipy.org/doc/numpy/reference/generated/numpy.stack.html

相关问题