Jeff
Jeff

Reputation: 8431

Check whether all elements of a NumPy array match a condition

For a given 2 dimentional arrays such as below, i need to check if all the elements are less than 0.2.

a = np.array([[0.26002, 0.13918, 0.6008 ],
              [0.2997 , 0.28646, 0.41384],
              [0.41614, 0.36464, 0.21922]])

Here is my code, based on this question.

 res = abs(a<0.2)
 all(i==True for i in res)

But the code complains with

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Upvotes: 7

Views: 11784

Answers (1)

cs95
cs95

Reputation: 403208

The key is to use np.all here:

(np.abs(a) < 0.2).all()
# False

(a < 1).all()
# True

Upvotes: 14

Related Questions