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.array
s.
np.all(arr)
(orarr.all()
) checks whether all elements inarr
areTrue
.np.any(arr)
(orarr.any()
) checks whether at least one element inarr
isTrue
.
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]