31

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
1
  • 1
    You should provide Short, Self Contained, Correct (Compilable), Example sscce.org. Not to mention that 'not working' is not a description of the problem. Commented Sep 21, 2013 at 0:01

2 Answers 2

76

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]),)
Sign up to request clarification or add additional context in comments.

4 Comments

Can you do that to with wildcards - say if the first "0." would be permitted as "any value" ?
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.
Ok - so wildcards are out of the question. Excellent clarification. Thx
Does np.where really return index? Why the document shows a different thing? numpy.org/doc/stable/reference/generated/numpy.where.html
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])

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.