Python

Count the Number of Zeros in the NumPy Array

This article will discuss how to count the number of zero elements in a NumPy array.

Method #1 – NumPy count_nonzero() Function

The first method we can use to determine the number of zero elements in an array is the count_nonzero() function

As the name suggests, this function returns the number of non-zero elements in an array.

We can take the value from this function and subtract it from the total number of elements in an array. This should give us the total number of zero elements.

To explore this function further, check the related link for a tutorial on numpy Count Nonzero. For example, to get the number of zero elements in a 1D array using the count_nonzero() function, we can do:

# import numpy
import numpy as np

arr = np.array([0,1,0,1,1,0,0,1,0])
print(f"number of non-zero: {np.count_nonzero(arr)}" )
print(f"number of zeros: {arr.size - np.count_nonzero(arr)}")

The example code above uses the arr.size property – the value from the count_nonzero function to get the number of zero elements in the array.

The resulting value is as shown:

number of non-zero: 4
number of zeros: 5

NOTE: Python treats a false value as Zero. Hence, we can use the above method to determine the number of false values in an array.

An example is illustrated in the code below:

arr = np.array([True, False, True, False])
print(f"number of non-zero: {np.count_nonzero(arr)}" )
print(f"number of zeros: {arr.size - np.count_nonzero(arr)}")

In this case, our input array holds Boolean elements.

The resulting output is as shown:

number of non-zero: 2
number of zeros: 2

Method #2

We can also use the NumPy where method to determine the number of zero elements in a given array.

The where function allows us to specify a Boolean condition and return the elements in the array that match said condition.

To use this function for our needs, we can run the code:

arr = np.array([0,1,0,1,1,0,0,1,0])
no_zeros = arr[np.where(arr==0)]
print(f"number of zeros: {no_zeros.size}")

In this case, we are using the indexing notation with the where condition.

The code above should return an array with the indices of the zero elements in the input array.

We then use the size property to get the total number of elements. The resulting value is as shown:

number of zeros: 5

Conclusion

In this article, we discussed two methods you can use to get the number of zero elements in a NumPy array.

Stay tuned for more!!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list