2015-02-05 25 views

回答

3

你可以使用的numpy.where的一個參數形式:

idxs = np.where(labels == lbl)[0] 

,或者等價地,使用numpy.nonzero:(!感謝喬)

idxs = np.nonzero(labels == lbl)[0] 

,或者更好的可讀性,

idxs = np.flatnonzero(labels == lbl) 

例如,

In [332]: np.random.seed(1) 

In [333]: labels = np.random.randint(5, size=10) 

In [334]: labels 
Out[334]: array([3, 4, 0, 1, 3, 0, 0, 1, 4, 4]) 

In [335]: [i for i,x in enumerate(labels) if x==lbl] 
Out[335]: [3, 7] 

In [336]: np.where(labels == lbl)[0] 
Out[336]: array([3, 7]) 

使用np.where是多少,比列表修真大型陣列更快:

In [339]: labels = np.tile(labels, 1000) 

In [340]: labels.shape 
Out[340]: (10000,) 

In [341]: %timeit np.where(labels == lbl)[0] 
10000 loops, best of 3: 45.9 µs per loop 

In [342]: %timeit [i for i,x in enumerate(labels) if x==lbl] 
100 loops, best of 3: 5.31 ms per loop 

In [343]: 5310/45.9 
Out[343]: 115.68627450980392 
+0

顯然我需要等待9分鐘才能接受此答案 – user4535015 2015-02-05 22:45:44

+2

正如旁註所示,還有'np.flatnonzero(...)'避免了對[[0]]的需要:http:// docs .sipy.org/doc/numpy/reference/generated/numpy.flatnonzero.html – 2015-02-09 16:55:22

1

我沒有代表。以評論答案...然而,請記住,當使用numpy.where「標籤」必須是一個numpy數組。

Codelifting unutbu的回答是:

idxs = np.where(np.array(labels) == lbl)[0]

只是要清楚:正確的答案被unutbu製造。

+0

確實,最後使用類似的東西 - np.asarray – user4535015 2015-02-05 23:52:24

+0

PS:我會upvote你的答案,但缺乏代表這樣做。 :-) – user4535015 2015-02-05 23:53:52