numpy.any() checks whether at least one element in an array evaluates to True. It returns a Boolean value or a Boolean array when an axis is specified.
Example: This example checks whether an array contains at least one non-zero value.
import numpy as np
arr = [0, 0, 5]
print(np.any(arr))
Output
True
Explanation: np.any() returns True because the array contains the non-zero value 5.
Syntax
numpy.any(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)
Parameters:
- a: Input array or array-like object.
- axis: Axis along which the elements are evaluated. By default, all elements are checked.
- out (Optional): array where the result is stored.
- keepdims: If True, keeps the reduced axes in the result with size one.
- where (Optional): condition that specifies which elements are included.
Examples
Example 1: This example checks whether at least one value in a Boolean array is True.
import numpy as np
arr = [False, False, True]
print(np.any(arr))
Output
True
Explanation: np.any(arr) returns True because the array contains one True value.Â
Example 2: This example checks the values column-wise by setting axis=0.
import numpy as np
arr = np.array([[0, 1], [0, 0]])
print(np.any(arr, axis=0))
Output
[False True]
Explanation:Â axis=0 makes np.any() evaluate each column. The first column contains only zeros, while the second column contains 1.
Example 3: This example checks whether any value in the array is greater than 10.
import numpy as np
arr = np.array([4, 7, 12, 3])
print(np.any(arr > 10))
Output
True
Explanation: arr > 10 creates a Boolean array and np.any() returns True because 12 satisfies the condition.