The any() function of NumPy

Overview:

  • The numpy.any() applies logical OR across the rows, columns or on the entire ndarray to check whether any of the elements in the given axis evaluate to True.

  • Applying numpy.any() results in the reduction of the ndarray. When the axis = None, the whole ndarray is reduced to single Boolean value-True or False.

  • The any() function differs from all(), that the all() reduces an ndarray using logical AND. The object oriented versions of these functions are compared with examples in the all() and any() methods of numpy.ndarray.

Example:

# Example Python program that uses any() method
# to find whether any of the elements on a row/column/array
# evaluates to True.
import numpy 
from random import randrange

# Create an ndarray and fill with random Boolean values
n1 = numpy.ndarray(shape = (3, 4), dtype = numpy.int32)

for i in range(0, 3):
    for j in range(0, 4):
        n1[i][j] = randrange(2)

print("The ndarray:")
print(n1)
# Apply any() - axis=1
anyResults = numpy.any(n1, axis = 1)
print("Results of any() row-wise:")
print(anyResults)

# Apply any() - axis=0
anyResults = numpy.any(n1, axis = 0)
print("Results of any() column-wise:")
print(anyResults)

Output:

The ndarray:

[[1 1 0 0]

 [0 1 0 0]

 [0 0 1 0]]

Results of any() row-wise:

[ True  True  True]

Results of any() column-wise:

[ True  True  True False]

 


Copyright 2024 © pythontic.com