NumPy Any: Understanding np.any()

Posted 2021-10-21

The np.any() function tests whether any element in a NumPy array evaluates to true:

np.any(np.array([[1, 0], [0, 0]]))

# Expected result
# True

The input can have any shape and the data type does not have to be boolean (as long as it’s truthy). If none of the elements evaluate to true, the function returns false:

np.any(np.array([[0, 0], [0, 0]]))

# Expected result
# False

Passing in a value for the axis argument makes np.any() a reducing operation. Say we want to know which rows in a matrix have any truthy elements. We can do that by passing in axis=-1:

np.any(np.zeros((2, 3)), axis=-1)

# Expected result
# array([False, False])

There are two rows and for each of them, none of the elements evaluate to true. The -1 value here is shorthand for “the last axis”.

Easy enough! NumPy also has a function called np.all() which has the same API as np.any() but returns true when all of the elements evaluate to true.

If you want to improve your knowledge of NumPy, I recommend Chapter 2 of the Python Data Science Handbook. I get commissions for purchases made through this link. So you can learn more about NumPy and support the blog at the same time!

Connect

Contact

ben [at] sparrow [dot] dev

Email List