2013-09-20 54 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

好的 - 所以通配符是不可能的。优秀的说明。谢谢 –