30

I am new to numpy and I am implementing clustering with random forest in python. My question is:

How could I find the index of the exact row in an array? For example

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

and I look for [0. 0. 3.] and get as result 1(the index of the second row).

Any suggestion? Follows the code (not working...)

    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
user2801023
  • 487
  • 1
  • 4
  • 8
  • 1
    You should provide Short, Self Contained, Correct (Compilable), Example http://www.sscce.org/. Not to mention that 'not working' is not a description of the problem. – zero323 Sep 21 '13 at 00:01

2 Answers2

73

Why not simply do something like this?

>>> 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]),)
Daniel
  • 19,179
  • 7
  • 60
  • 74
  • Can you do that to with wildcards - say if the first "0." would be permitted as "any value" ? – root-11 May 29 '15 at 16:38
  • 1
    If I understand you correctly try: `a[:,1:] == np.array([0, 3])` instead of `a == b`. So what we do is just slice off the first column and compare as shown. – Daniel May 29 '15 at 17:41
  • Ok - so wildcards are out of the question. Excellent clarification. Thx – root-11 May 29 '15 at 21:57
  • Does np.where really return index? Why the document shows a different thing? https://numpy.org/doc/stable/reference/generated/numpy.where.html – Shuangjun Liu Jun 28 '21 at 22:13
0
a=[[ 0.,5.,  2.],
[ 0. , 0.,  3.],
[ 0.,  0.,  0.]]

for i in enumerate(a):
    if i[1]==[ 0. , 0.,  3.]:
        print(i[0])
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 11 '21 at 11:11