通过获取 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
"""
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)
| 归档时间: |
|
| 查看次数: |
6004 次 |
| 最近记录: |