Check if All Elements are True - NumPy all()


Numpy all()

Numpy all() function checks if all elements in the array, along a given axis, evaluate to True.

If all elements evaluate to True, then numpy.all() returns True, else it returns False.

Examples

1. Check if all elements in array are True

In this example, we will take a Numpy Array with all its elements as True. We will pass this array as argument to all() function. The function should return True, since all the elements of array evaluate to True.

Python Program

import numpy as np

arr = np.array([[True,True],[True,True]])
result = np.all(arr)
print(result)

Output

True

2. Some elements are False in array

In this example, we will take a Numpy Array with some of its elements as False. We will pass this array as argument to all() function. The function should return False, since all the values of the given array does not evaluate to True.

Python Program

import numpy as np

arr = np.array([[True,True],[False,False]])
result = np.all(arr)
print(result)

Output

False

3. Check if all elements in array are True along an axis

In this example, we take a NumPy Array with boolean values. We check if all the elements in the array are True along specified axis axis=1 using numpy.all() function.

Python Program

import numpy as np

arr = np.array([[True,True], [True,False], [True,False]])
result = np.all(arr, axis=1)
print(result)

Output

[ True False False]

Explanation

numpy.all() along axis 1

Now, we shall apply the numpy.all() function along axis=0.

Python Program

import numpy as np

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

Output

[ True False]

Explanation

numpy.all() along axis 0

Summary

In this NumPy Tutorial, we learned how to use numpy.all() function to check if all elements are True, along an axis if given, with the help of example programs.