Write a NumPy program to count the number of elements equal to zero in the given array.

This NumPy program will take an array as an input and count the number of elements equal to zero in it. It will then output the count of elements equal to zero as an integer. This program can be used to quickly check the number of elements that have the value of zero in an array.


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.

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

x