Let’s check how many zeros the are in your array. We will use Numpy count_nonzero function.
Using count_nonzero method
To check how many zeros you have in your array you need to know count_nonzero function.
Just put my_array==0 as an argument as in below example.
import numpy as np my_array = np.array([0, 7, 6, 5, 0, 0, 0, 7, 0, 3, 2, 0]) zeros = np.count_nonzero(my_array == 0) print(f"There are {zeros} zeros in my array.")
As you can see Python printed out the number of zeros from the array.
Using where method
Another way to count number of zeros in an array would be to use Numpy where method.
import numpy as np my_array = np.array([0, 7, 6, 5, 0, 0, 0, 7, 0, 3, 2, 0]) zeros = my_array[np.where(my_array == 0)] print(f"There are {zeros.size} zeros in my array.")
Thanks to Numpy where function it is possible to create additional zeros array which contains only zeros. The answer would be the size of zeros array.
The output would be:
There are 6 zeros in my array.