Mjd Al Mahasneh
Mjd Al Mahasneh

Reputation: 47

How to get the index of a particular row using column values in numpy?

So if I have the following array arr:

>>> arr
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

Now if I want to acquire the first row, I would do something like this :

>>> arr[0]
array([0, 1, 2, 3, 4])

However, when I use np.where to locate a particular row, e.g.:

>>> np.where(arr == [0,1,2,3,4])

I get this output!

(array([0, 0, 0, 0, 0, 3, 3, 3, 3, 3], dtype=int64), 
array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=int64))

However, this is not what am after. I would like to get the row indices instead. e.g.:

(array([0, 3], dtype=int64)

Is there a way to achieve that? any advice is very much appreciated!

Upvotes: 0

Views: 80

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

I think you want to check if the rows are equal to a given array. In which case, you need all:

np.where((arr == [0,1,2,3,4]).all(1))
# (array([0, 3]),)

Upvotes: 2

Related Questions