在numpy数组中获取特定值的索引

4

我有以下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函数可以做同样的事情?

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]) 转换为数组以便清晰明了,然后使用以下方法之一:
np.where(arr==0) (array([ 0, 1, 2, 4, 5, ..., 21, 22, 23, 24, 25]),) 切片 where [0] 只获取索引。
- user1121588
你需要的是numpy.argwhere吗?类似于numpy.argwhere(arr == 0)这样的东西。 - chappers
2个回答

5
您可以使用@chappers在评论中提到的numpy.argwhere
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)

3
>>> 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])
>>> (arr==0).nonzero()[0]
array([ 0,  1,  2,  4,  5,  6,  7,  8,  9, 10, 12, 14, 16, 17, 18, 19, 20,
       21, 22, 23, 24, 25])

1
谢谢@John,nonzero末尾的[0]是什么意思? - user308827
4
nonzero函数返回一个由数组组成的元组,对应于arr的每个维度。你的数组只有一个维度,但是你仍然需要在那里加入[0]来将它从元组中取出。 - John La Rooy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接