How to check if a NumPy array has all zeros in Python
In this tutorial, we are going to learn about how to check if a NumPy array has all zeros in Python with the help of examples.
In Python NumPy is used to work with arrays. The array object in NumPy is called ndarray.
Consider, that we are having the following NumPy array contains only zeros in it.
import numpy as np
prices = np.array([0, 0, 0, 0])
Using any() function
To check if an NumPy array contains all zeros, we can use the any() function in Python.
The any() function accepts the NumPy array as an argument and checks whether any of the elements in array evaluates to the boolean value True or not. If any of the element is evaluates to true then it returns true. If all the elements contains zero values it evaluates to False.
Here is an example:
import numpy as np
prices = np.array([0, 0, 0, 0])
if not np.any(prices):
print('Array contains all zeros')
else:
print('Array contains non zero values')
Output:
Array contains all zeros
Using the numpy.count_nonzero()
The numpy.count_nonzero() function takes the numpy array as argument and returns the number of non zero values in the array. By using that we can check if a array contains all zeros or not.
Here is an example:
import numpy as np
prices = np.array([0, 0, 0, 0])
if np.count_nonzero(prices) == 0:
print('Array contains all zeros')
else:
print('Array contains non zero values')
Additional resources
You can also check following tutorials in Python: