Summary: in this tutorial, you’ll learn how to use the numpy any()
function that returns True
if any element in an array evaluates True
.
Introduction to the numpy any() function
The numpy any()
function returns True
if any element in an array (or along a given axis) evaluates to True
.
Here’s the syntax of the any
function:
numpy.any(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)
Code language: Python (python)
In this syntax, a
is a numpy array or any object that can be converted to an array e.g., a list.
Typically, the input array contains numbers. In the boolean context, all non-zero numbers evaluate to True
while zero evaluates to False
. Therefore, the any()
function returns True
if any number in the array is nonzero or False
if all numbers are zero.
NumPy any() function examples
Let’s take some examples of using the any()
function.
1) Using numpy any() function on 1-D array examples
The following example uses the any()
function to test whether any number in an array are non-zero:
import numpy as np
result = np.any([0, 1, 2, 3])
print(result)
Code language: Python (python)
Output:
True
Code language: Python (python)
The result is True
because the array of three non-zero numbers.
import numpy as np
result = np.any(np.array([0, 0]))
print(result)
Code language: Python (python)
Output:
False
Code language: Python (python)
This example returns False
because all numbers in the array are zero. In fact, you can pass any object that can be converted into a list to the any()
function. For example:
import numpy as np
result = np.any([0, 0])
print(result)
Code language: Python (python)
Output:
False
Code language: Python (python)
2) Using numpy any() function with a multidimensional array example
The following example uses the any()
function to test if any elements of a multidimensional array evaluate to True
:
import numpy as np
a = np.array([[0, 1], [2, 3]])
result = np.any(a)
print(result)
Code language: Python (python)
Output:
True
Code language: Python (python)
Also, you can evaluate elements along an axis by passing the axis
argument like this:
import numpy as np
a = np.array([
[0, 0],
[0, 1]
])
result = np.any(a, axis=0)
print(result)
Code language: Python (python)
Output:
[False True]
Code language: Python (python)
And axis-1:
import numpy as np
a = np.array([
[0, 0],
[0, 1]
])
result = np.any(a, axis=1)
print(result)
Code language: Python (python)
Output:
[False True]
Code language: Python (python)
Summary
- Use the numpy
any
function to test whether any element in an array or along an axis evaluates toTrue
.