Numpy: search for the first matching string
If I have a numpy array like this:
import numpy as np
x = np.array([[0,1],[0,2],[1,1],[0,2]])
How to return the index of the first row that matches [0,2]
?
For lists it’s easy to use index
:
[[0,1],[0,2],[1,1],[0,2]]
l.index([0,2])
> 1
And I know that it numpy
has a function numpy.where
, but I'm not sure what to do with the output numpy.where
:
np.where(x==[0,2])
> (array([0, 1, 1, 3, 3]), array([0, 0, 1, 0, 1]))
There also numpy.argmax
, but it also does not return what I am looking for, it is just an index1
np.argmax(x == [0,2], axis = 1)
+4
C_z_
source
share1 answer
[0,2]
, broadcasting
x
, , x
. , TRUE
.all(1)
. , , np.where
np.nonzero
. -
In [132]: x
Out[132]:
array([[0, 1],
[0, 2],
[1, 1],
[0, 2]])
In [133]: search_list = [0,2]
In [134]: np.where((x == search_list).all(1))[0][0]
Out[134]: 1
In [135]: np.nonzero((x == search_list).all(1))[0][0]
Out[135]: 1
+4
Divakar