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  Python in Cryptocurrency Analysis

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. where() returns indices tuple; indexing my_array with those indices gives filtered array of zeros; .size counts them. But misleading heading.


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  How to save array as csv file with Numpy?

The output would be:

There are 6 zeros in my array.

count_nonzero is simpler for counting; where() returns indices (more complex); simpler approach is (my_array == 0).sum().