Let’s learn how to count how many zeros you have in array. There are two different Python methods you can use.
Using a count_nonzero method
We will use really unexpected Numpy method. For sure you will be surprised. To count a zeros frequency in your matrix you need to use count_nonzero function. Then as a parameter you should use your array == 0. Believe me it works.
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}")
As you can see count_nonzero function counted zeros.
Using a where method
The second way to calculate zeros in an array is to use where Python method.
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.
The output is the same.
There are 4 zeros in my array.