NumPy np.any()

The any() function in NumPy is used to test whether an element in a given array evaluates to True.

Let us discuss.

Function Syntax

The function has a relatively simple syntax as shown below:

numpy.any(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)

Function Parameters

The function accepts the following parameters:

  1. a – refers to the input array or array_like object.
  2. 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.
  3. out – specifies an output array to store the output.
  4. 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
import numpy as np
arr = np.array([True, False, True, True])

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:

arr = np.array([1,0,1,np.nan, 0])

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.

arr = np.array([[True, False, True], [True, False, False]])
print(np.any(arr, axis=0))

The above code should return an array as shown:

[ True False  True]

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:

arr = np.array([[True, False, True], [True, False, False]])
print(np.any(arr, axis=-1))

This returns:

[ True  True]

Example #5

To save the output to a different array, we can do:

arr = np.array([[True, False, True], [True, False, False]])
save = np.array([True, False])
np.any(arr, axis=-1, out=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:

[ True  True]

You can also replace the values of the array with integers.


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!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list