Let us discuss.
Function Syntax
The function has a relatively simple syntax as shown below:
Function Parameters
The function accepts the following parameters:
- a – refers to the input array or array_like object.
- axis – the axis parameter defines the logical OR reduction along which axis is carried out. If set to None, the array will flatten the array.
- out – specifies an output array to store the output.
- where – specifies which elements to include in the evaluation process.
Function Return Value
The function returns an array containing Boolean values.
NOTE: Any value that is not equal to zero is treated as true. These include NaN and positive and negative infinity values.
Example #1
The example below shows how to use the any() function in a one-dimensional array holding Boolean values.
import numpy as np
arr = np.array([True, False, True, True])
print(np.any(arr))
The code above should test whether any of the elements in the provided array is equal to True.
The resulting output is as shown:
Example #2
Condier the following example:
print(np.any(arr)
The code should return True as the array contains True values such as 1 and NaN.
Example #3
Take the same operation performed on a 2d array along a specific axis.
print(np.any(arr, axis=0))
The above code should return an array as shown:
Example #4
You can also pass a negative axis value, in which the case the function will count from the last to first indices.
An example is as shown:
print(np.any(arr, axis=-1))
This returns:
Example #5
To save the output to a different array, we can do:
save = np.array([True, False])
np.any(arr, axis=-1, out=save)
print(save)
In this example, we have an array called save with the same shape as the output value. We then use the out parameter to save the output of the any() function to the save array.
The resulting array is as shown:
You can also replace the values of the array with integers.
Conclusion
In this article, we explored the NumPy any function, which allows us to test if any element in an array evaluates to True along a given axis.
Happy coding!!