我知道了。 numpy 数组:
arr = [0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1]
这就是我如何获取数组中所有 0 的索引:
inds = []
for index,item in enumerate(arr):
if item == 0:
inds.append(index)
是否有一个 numpy 函数可以做同样的事情?
最佳答案
你可以使用 numpy.argwhere
正如@chappers 在评论中指出的那样:
arr = np.array([0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1])
In [34]: np.argwhere(arr == 0).flatten()
Out[34]:
array([ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25], dtype=int32)
或者使用 astype(bool)
的逆函数:
In [63]: (~arr.astype(bool)).nonzero()[0]
Out[63]:
array([ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25], dtype=int32)
关于python - 获取numpy数组中特定值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34126230/