gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:42:02 24 4
gpt4 key购买 nike

来自 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(数组)

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

np.argwhere(数组)

它等价于np.transpose(np.nonzero(array))

print(np.argwhere(A))
"""
[[0 0]
[0 2]
[1 1]
[1 2]
[2 0]]
"""

关于python - 获取二维数组的非零元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44092848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com