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. Counting zero elements in arrays is used for tasks such as identifying missing data points (where zeros might represent null values) or analyzing data distributions where the presence of zeros is significant.

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. The count_nonzero function is designed to count the number of non-zero elements in an array. By using the condition my_array == 0 within it, we effectively reverse the logic, instructing it to count the elements that are zero.

See also  How to convert array to binary?

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.

Using where method

Another way to count the number of zeros in an array is to use the Numpy where method. The count_nonzero returns the indices of the elements that satisfy a given condition. In this case, it returns the indices of all zero elements, allowing us to then determine their count by checking the size of the resulting array of indices.


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  Handling FloatingPointError: Ensuring Numerical Stability in NumPy

The output would be:

There are 6 zeros in my array.

The choice between count_nonzero and where depends on whether you simply need the total count (count_nonzero) or require the indices of the zero elements for further manipulation (where).