2013-10-23 138 views
14

我需要查找數組中發生的多個最小值的索引。我很熟悉np.argmin,但它給了我一個數組中第一個最小值的索引。例如。在Python中查找給定數組中最小值的索引

a = np.array([1,2,3,4,5,1,6,1])  
print np.argmin(a) 

這給我0,而不是我期待,0,5,7。

謝謝!

+6

嘗試'np.where(一== a.min())' –

+0

是啊!這項工作。 – user2766019

+0

[在列表中使用max()/ min()獲取返回的最大值或最小值項的索引](http://stackoverflow.com/questions/2474015/getting-the-index-of-the-返回最大或最小項目使用最大分鐘在列表中) – mlt

回答

20

這應該做的伎倆:像你期望它在這種情況下

a = np.array([1,2,3,4,5,1,6,1]) 
print np.where(a == a.min()) 

argmin不返回一個列表。

+1

不,它沒有。而且,你正在覆蓋一個內置函數'min'。 –

+1

@BasSwinckels你錯過了我的編輯。定期分鐘正如您所指出的那樣正常工作。 –

3

也許

mymin = np.min(a) 
min_positions = [i for i, x in enumerate(a) if x == mymin] 

它會給[0,5,7]。

+0

不,它沒有,因爲您正在比較最小的索引,即0。 –

+0

EDITED,使用min而不是argmin,對不起。 – tonjo

+0

它現在工作,所以投票下來是不合適的;) – tonjo

1

我認爲這將是最簡單的方法,雖然它沒有使用任何花哨的功能numpy的

a  = np.array([1,2,3,4,5,1,6,1])           
min_val = a.min()                

print "min_val = {0}".format(min_val)           

# Find all of them               
min_idxs = [idx for idx, val in enumerate(a) if val == min_val]    
print "min_idxs = {0}".format(min_idxs) 
相關問題