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

Time:10-21

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?

CodePudding user response:

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.

CodePudding user response:

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]

CodePudding user response:

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()]

CodePudding user response:

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]
  • Related