This tutorial will discuss about unique ways to check if all elements in numpy array are false.
Table Of Contents
Technique 1: Using numpy.all() method
We can use the numpy.all()
method to check if all elements of a NumPy array are False or not.
Compare the NumPy array with a boolean value False
, and it will return a NumPy Array of boolean values. A True
value in this boolean NumPy Array represents that the corresponding value in the original array is False
. Then to confirm if all the values in this boolean array are True or not, pass this boolean array to the numpy.all()
method. If it returns True, then it means that all the values in the orignal NumPy array are False
.
Let’s see the complete example,
import numpy as np # Create an example NumPy array of boolean values arr = np.array([False, False, False, False, False]) # Check if NumPy array contains only False Values if np.all(arr == False): print("All elements in NumPy Array are False") else: print("Not all elements in NumPy Array are False")
Output
All elements in NumPy Array are False
Technique 2: Using numpy.count_nonzero() method
As False
in Python evaluates to zero. So, we can call the count_nonzero()
method of NumPy module to get the count of non-zero or non-False values in a NumPy Array. If it returns zero, then it means that all the values in NumPy array are False.
Frequently Asked:
- Check if NumPy Array contains only empty strings – Python
- Check if a NumPy Array is in descending order
- Check if a NumPy Array contains a specific string
- Check if all elements in a NumPy array are unique
Let’s see the complete example,
import numpy as np # Create an example NumPy array of boolean values arr = np.array([False, False, False, False, False]) # Check if NumPy array contains only False Values if np.count_nonzero(arr) == 0: print("All elements in NumPy Array are False") else: print("Not all elements in NumPy Array are False")
Output
All elements in NumPy Array are False
Summary
We learned about two different ways to check if all values in a NumPy Array are False or not in Python.