NumPy: How to Count Number of Elements Equal to Zero


You can use the following basic syntax to count the number of elements equal to zero in a NumPy array:

import numpy as np

np.count_nonzero(my_array==0)

This particular example will return the number of elements equal to zero in the NumPy array called my_array.

The following example shows how to use this syntax in practice.

Example: Count Number of Elements Equal to Zero in NumPy Array

The following code shows how to use the count_nonzero() function to count the number of elements in a NumPy array equal to zero:

import numpy as np

#create NumPy array
my_array = np.array([2, 0, 0, 4, 5, 9, 12, 0, 4, 13, 15, 19])

#count number of values in array equal to zero
np.count_nonzero(my_array==0)

3

From the output we can see that 3 values in the NumPy array are equal to zero.

We can manually look at the NumPy array to verify that there are indeed three elements equal to zero in the array.

If you would instead like to count the number of elements not equal to zero, you can use the count_nonzero() function as follows:

import numpy as np

#create NumPy array
my_array = np.array([2, 0, 0, 4, 5, 9, 12, 0, 4, 13, 15, 19])

#count number of values in array not equal to zero
np.count_nonzero(my_array)

9

From the output we can see that 9 values in the NumPy array are not equal to zero.

Note: If you have any NaN values in your NumPy array, the count_nonzero() function will count each NaN value as an element not equal to zero.

Additional Resources

The following tutorials explain how to perform other common operations in Python:

How to Calculate the Mode of NumPy Array
How to Map a Function Over a NumPy Array
How to Sort a NumPy Array by Column

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *