This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 6: NumPy functions

Truth value functions

face Josiah Wang

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) (or arr.all()) checks whether all elements in arr are True.
  • np.any(arr) (or arr.any()) checks whether at least one element in arr is True.

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]