簡體   English   中英

獲取numpy數組中特定值的索引

[英]Getting indices of a specific value in numpy array

我有這個人。 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)
>>> 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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM