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

时间:2015-12-07 04:02:05

标签: python numpy

我有这个人。 numpy数组:

inds = []
for index,item in enumerate(arr):     
    if item == 0:
        inds.append(index)

这就是我获取数组中所有0的索引的方法:

image

是否有一个numpy函数来做同样的事情?

2 个答案:

答案 0 :(得分:2)

>>> 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 :(得分:2)

您可以使用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)