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

Python 获取numpy数组中特定值的索引,python,numpy,Python,Numpy,我有福勒。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函数可以实现同样的功能?正如@chappers在评论中指出的那样: >>> a

我有福勒。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函数可以实现同样的功能?

正如@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])
>>> (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])
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)
或与
aType(bool)
相反:


arr=np.数组([0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1])为清晰起见,转换为数组,然后…>>>其中(arr==0)(数组([0,1,2,4,5,…,21,22,23,24,25])是一种方法。用[0]将where切分,只是为了得到你想要的指示?类似于
numpy.argwhere(arr==0)
谢谢@John,非零结尾的[0]是做什么的?@user308827,
nonzero
返回数组元组,数组的每个维度一个。您只有一个维度,但仍然需要
[0]
将其从元组中拉出
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)