Introduction to NumPy and Matplotlib
Chapter 6: NumPy functions
Truth value functions
Let’s discuss a few more useful functions.
Just like Python’s all() and any() built-in functions, NumPy also provides its equivalent optimised for np.arrays.
np.all(arr)(orarr.all()) checks whether all elements inarrareTrue.np.any(arr)(orarr.any()) checks whether at least one element inarrisTrue.
Note: NaNs (np.nan), positive infinity (np.inf) and negative infinity (-np.inf) are all considered True because they are non-zero.
>>> print(np.all(np.array([True, True, True])))
True
>>> print(np.all(np.array([True, True, False])))
False
>>> print(np.any(np.array([True, False, False])))
True
>>> print(np.any(np.array([False, False, False])))
False
For multidimensional arrays, you can also apply np.any() and np.all() across a specific axis.
>>> x = np.array([[True, True, False, False], [True, False, True, False]])
>>> print(np.all(x, axis=0))
[ True False False False]
>>> print(np.any(x, axis=0))
[ True True True False]
>>> print(np.all(x, axis=1))
[False False]
>>> print(np.any(x, axis=1))
[True True]