You will learn how to count the number of zeros in an array using two different Python methods: count_nonzero() and where().
Using the count_nonzero() Method
The count_nonzero() method is a simple and efficient way to count the number of zeros in an array. 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.
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:
As you can see count_nonzero function counted zeros.
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.
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.")
This time zeros_frequency will provide an array of zeros. To calculate the number of zeros simply, you need to return the size of that array.
This code outputs the same output as the previous example.
There are 4 zeros in my array.