2

I have a numpy array and I want to find the elements satisfying my condition The codes are as below:

import numpy as np
a = np.array([[1, 2], [1, 3], [1, 2]])
b = np.array([1, 2])
c = (a == b) 

The results are

[[ True  True]
[ True False]
[ True  True]]

But what I want is [True, False, True] or the indices [0, 2].

Although I can achieve this by list comprehension, like

c = [all(b==x) for x in a]

But I want to find this element in a 3d matrix in the future, like

a = np.array([[[1, 2], [1, 3], [1, 2]], 
         [[7, 2], [1, 2], [4, 2]]])

I want the index like [[0, 0], [0, 2], [1, 1]]

How should I achieve this by numpy?

1 Answer 1

2

How about numpy.all with axis:

Code:

np.all(a == b, axis=1)

Test Code:

a = np.array([[1, 2], [1, 3], [1, 2]])
b = np.array([1, 2])
c = np.all(a == b, axis=1)
print(c)

Results:

[ True False  True]
Sign up to request clarification or add additional context in comments.

1 Comment

It works and works for 3D matrix as well, thanks so much

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.