【发布时间】:2017-05-21 03:24:00
【问题描述】:
从Getting indices of both zero and nonzero elements in array,我可以像这样在 numpy 中获取一维数组中非零元素的索引:
indices_nonzero = numpy.arange(len(array))[~bindices_zero]
有没有办法将它扩展到二维数组?
【问题讨论】:
从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(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]]
"""
【讨论】:
numpy 函数。
np.nonzero,或者它的别名np.where几乎不需要特别解释..
np.argwhere 另一个有趣的技巧(检查它的代码)
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
【讨论】: