2013-09-20 56 views
15

我是numpy的新手,我正在用python中的隨機森林實現集羣。我的問題是:Numpy Array按行搜索行索引

我怎麼能找到一個數組中的確切行的索引?例如

[[ 0. 5. 2.] 
[ 0. 0. 3.] 
[ 0. 0. 0.]] 

對於我找[0. 0. 3.]並獲得儘可能結果1(第二行的索引)。

有什麼建議嗎?按照代碼(不工作...)

for index, element in enumerate(leaf_node.x): 
     for index_second_element, element_two in enumerate(leaf_node.x): 
      if (index <= index_second_element): 
       index_row = np.where(X == element) 
       index_column = np.where(X == element_two) 
       self.similarity_matrix[index_row][index_column] += 1 
+1

您應該提供簡短,自包含,正確(可編譯),示例http://www.sscce.org/。更何況「不工作」不是對問題的描述。 – zero323

回答

39

爲什麼不簡單地做這樣的事情?

>>> a 
array([[ 0., 5., 2.], 
     [ 0., 0., 3.], 
     [ 0., 0., 0.]]) 
>>> b 
array([ 0., 0., 3.]) 

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

>>> np.all(a==b,axis=1) 
array([False, True, False], dtype=bool) 

>>> np.where(np.all(a==b,axis=1)) 
(array([1]),) 
+0

你可以這樣做與通配符 - 說如果第一個「0」。將被允許​​爲「任何價值」? –

+1

如果我正確理解你,請嘗試:'a [:,1:] == np.array([0,3])'而不是'a == b'。因此,我們所做的只是切斷第一列並如圖所示進行比較。 – Daniel

+0

好的 - 所以通配符是不可能的。優秀的說明。謝謝 –