Do you want to know how many elements in your numpy array is 0? How many elements are non-zero. If yes then you have come to the right place. In this entire tutorial, you will implement numpy count nonzero method in step by step.
Steps to Implement Numpy Count Nonzero method
Step 1: Import NumPy library
In this tutorial, I am using only NumPy library so import it using the import statement.
import numpy as np
Step 2: Create A Sample Numpy array
For the demonstration purpose, you have to create a NumPy array. Here I am finding zero or non-zero elements on both 1D and 2D array.
Let’s create them.
array_1d = np.array([1,2,0,0,4,5,0])
array([1, 2, 0, 0, 4, 5, 0])
2D Numpy array
array_2d = np.array([[1,2,0],[0,4,5],[0,0,1]])
array([[1, 2, 0], [0, 4, 5], [0, 0, 1]])
Step 3: Apply the Numpy count_nonzero() method.
Now after the creation let’s apply this function on 1D and 2D array.
Applying count nonzero() on 1D array
To find non-zero or zero elements in the 1D array, you have to just pass the array inside the count_nonzero() method.
Find the number of Non-zero elements
Number of zero elements.
array_1d.size - np.count_nonzero(array_1d)
Applying Numpy Count Nonzero on a 2D array
On 2 D there are three cases. One case is to find all non-zero elements on the entire array. The second is the number of non-zero elements for each row. And the last case is to find the number of non-zero elements for each column.
Case 1: Find the non-zero elements for an entire array
To find it you have to just pass your 2D array inside the numpy.count_nonzero().
Case 2: Find the non-zero elements for each row.
In this case, you have to add an extra argument inside the method and that is axis =1. It will find all the non-zero elements.
Case 3: Find the non-zero elements for each column.
In the same way, you can find all the non-zero elements of the 2D array by setting axis =0. Execute the lines of code.
To find the number of zeros elements you have to just subtract the count of non-zero elements with the array size.
array_2d.size - np.count_nonzero(array_2d)
If you want to count the zero or non-zero elements in the array the numpy.count_nonzero method is the best. These are the implementation of this method in python. There is another method to find non-zero elements and it is np.where() but it is not an efficient way to do so.
Hope you have liked this article on how to find zeros using the Numpy Count Nonzero method. If you have any queries then you can contact us for more information.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.