1

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?

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry if I wasn't clear but my question was how do I code it so that the program returns 1 given that I know that array [1 1 2] is a member of the matrix A.
0

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]

Comments

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

2 Comments

I don't think it works if my array is a numpy araay. I need to convert it to list instead.
I edited for 2D np.array
0
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.