3

Using numpy, I have a matrix called points.

   points
=> matrix([[0, 2],
        [0, 0],
        [1, 3],
        [4, 6],
        [0, 7],
        [0, 3]])

If I have the tuple (1, 3), I want to find the row in points that matches these numbers (in this case, the row index is 2).

I tried using np.where:

np.where(points == (1, 3))
=> (array([2, 2, 5]), array([0, 1, 1]))

What is the meaning of this output? Can it be used to find the row where (1, 3) occurs?

Vermillion
  • 1,238
  • 1
  • 14
  • 29
  • 1
    Divakar gave a nice answer, but you could also look at http://stackoverflow.com/questions/30145996/get-row-numbers-of-rows-matching-a-condition-in-numpy – jkr Nov 02 '16 at 14:29

1 Answers1

7

You were just needed to look for ALL matches along each row, like so -

np.where((a==(1,3)).all(axis=1))[0]

Steps involved using given sample -

In [17]: a # Input matrix
Out[17]: 
matrix([[0, 2],
        [0, 0],
        [1, 3],
        [4, 6],
        [0, 7],
        [0, 3]])

In [18]: (a==(1,3)) # Matrix of broadcasted matches
Out[18]: 
matrix([[False, False],
        [False, False],
        [ True,  True],
        [False, False],
        [False, False],
        [False,  True]], dtype=bool)

In [19]: (a==(1,3)).all(axis=1) # Look for ALL matches along each row
Out[19]: 
matrix([[False],
        [False],
        [ True],
        [False],
        [False],
        [False]], dtype=bool)

In [20]: np.where((a==(1,3)).all(1))[0] # Use np.where to get row indices
Out[20]: array([2])
Divakar
  • 218,885
  • 19
  • 262
  • 358