2015-06-04 192 views
4

我在Python中有兩個向量:PredictionsLabels。我想要做的是找出這兩個向量具有相同元素的一組索引。例如,讓我們說的載體是:如何找到Python中兩個向量具有相同元素的索引集合

Predictions = [4, 2, 5, 8, 3, 4, 2, 2] 

    Labels = [4, 3, 4, 8, 2, 2, 1, 2] 

所以索引集,其中兩個矢量具有相同的元素是:

Indices = [0, 3, 7] 

我怎樣才能得到這個在Python?沒有使用for-loops等。是否有內置函數,例如在numpy

謝謝你的幫助!

回答

6

這是numpy的做這件事的一種方法:

np.where(np.equal(Predictions, Labels)) 

這相當於:

np.equal(Predictions, Labels).nonzero() 

它將雖然返回一個元素的元組,因此要獲得實際的數組,加[0]如:

np.equal(Predictions, Labels).nonzero()[0] 
+0

謝謝你的幫助=)欣賞它 – jjepsuomi

3

對於兩個陣列a, b用:

a = np.array([1, 2, 3, 4, 5]) 
b = np.array([1, 3, 2, 4, 5]) 

np.equal(a,b)具有輸出相同a==b(這是更容易理解,首先,我認爲):

> array([ True, False, False, True, True], dtype=bool) 

的元件被檢查逐元素,然後創建布爾值的陣列。

np.where()檢查一些條件逐元素的數組:

np.where(a > 2) 
> (array([2, 3, 4]),) 

所以結合np.wherenp.equal是你想要的東西:

np.where(np.equal(a,b)) 
> (array([0, 3, 4]),) 

編輯:沒關係,剛纔看到我太慢了^^

+0

謝謝,感謝您的幫助:) – jjepsuomi

相關問題