Black Beard 53
Black Beard 53

Reputation: 65

Find the row index number of an array in a 2D numpy array

If I have a 2D numpy array A:

[[6 9 6]
 [1 1 2]
 [8 7 3]]

And I have access to array [1 1 2]. Clearly, [1 1 2] belongs to index 1 of array A. But how do I do this?

Upvotes: 1

Views: 49

Answers (4)

Talha Tayyab
Talha Tayyab

Reputation: 27297

import numpy as np
a = np.array([[6, 9, 6],
              [1, 1, 2],
              [8, 7, 3]])
b = np.array([1, 1, 2])

[x for x,y in enumerate(a) if (y==b).all()] # here enumerate will keep the track of index

#output
[1]

Upvotes: 0

imburningbabe
imburningbabe

Reputation: 792

arr1 = [[6,9,6],[1,1,2],[8,7,3]]
ind = arr1.index([1,1,2])

Output:

ind = 1

EDIT for 2D np.array:

arr1 = np.array([[6,9,6],[1,1,2],[8,7,3]])  
ind = [l for l in range(len(arr1)) if (arr1[l,:] == np.array([1,1,2])).all()]

Upvotes: 0

CrisPlusPlus
CrisPlusPlus

Reputation: 2292

Access the second row using the following operator:

import numpy as np                                                                                      
                                                                                                        
a = np.array([[6, 9, 6],                                                                                
              [1, 1, 2],                                                                                
              [8, 7, 3]])                                                                               
                                                                                                        
row = [1, 1, 2]                                                                                         
i = np.where(np.all(a==row, axis=1))                                                                    
print(i[0][0]) 

np.where will return a tuple of indices (lists), which is why you need to use the operators [0][0] consecutively in order to obtain an int.

Upvotes: 1

mozway
mozway

Reputation: 260335

One option:

a = np.array([[6, 9, 6],
              [1, 1, 2],
              [8, 7, 3]])
b = np.array([1, 1, 2])

np.nonzero((a == b).all(1))[0]

output: [1]

Upvotes: 0

Related Questions