How to count number of zeros in Numpy array?

Let’s check how many zeros there are in your array. We will use the Numpy count_nonzero function.

Numpy count number of zeros

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.")

Numpy count number of zeros

As you can see, Python printed out the number of zeros from the array.

See also  How to Generate Random Integers in Range with Numpy

Using where method

Another way to count the number of zeros in an array is to use the 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.

See also  Managing BufferError: Understanding Buffer Interface in NumPy

The output would be:

There are 6 zeros in my array.