Count how many zeros you have in array

You will learn how to count the number of zeros in an array using two different Python methods: count_nonzero and where.

Numpy count zeros

Using the count_nonzero Method

The count_nonzero function is used inversely to count the number of non-zero elements, but with a logical inversion, it effectively counts zeros. To use this method, you pass the array to the count_nonzero function. The function will return the number of elements in the array that are not equal to zero.

See also  How to create an immutable Numpy array?

For example, the following code counts the number of zeros in the array my_array:

import numpy as np

my_array = np.array([[1, 0, 5],
                    [5, 3, 0],
                    [0, 0, 2]])

zeros_frequency = np.count_nonzero(my_array == 0)
print(f"Count of zeroes in my array: \n{zeros_frequency}")

This code outputs the following:

Numpy count zeros

The output shows the count of zeros in the array as determined by the count_nonzero function.

Using the where Method

The where method is a more versatile method that can be used to count the number of zeros in an array, as well as other conditions. To use this method, you pass a Boolean expression to the where function. The function will return an array of the elements in the original array that satisfy the Boolean expression.

See also  Managing BufferError: Understanding Buffer Interface in NumPy

For example, the following code uses the where method to count the number of zeros in the array my_array:

import numpy as np

my_array = np.array([[1, 0, 5],
                    [5, 3, 0],
                    [0, 0, 2]])

zeros_frequency = my_array[np.where(my_array == 0)].size
print(f"There are {zeros_frequency} zeros in my array.")

In this approach, zeros_frequency captures the size of the array filtered by the condition, directly indicating the number of zeros.

See also  How to create numpy array with zeros?

This code outputs the same output as the previous example.

There are 4 zeros in my array.

You can also directly get the count using the .size attribute:

zeros_count = my_array[np.where(my_array == 0)].size
print(f"Number of zeros in the array: {zeros_count}")