In this tutorial, we will look at how to count zeros in a numpy array. We will also look at how to count zeros present in each row and each column of a 2d array.
How to count zeros in a numpy array?
You can use np.count_nonzero()
or the np.where()
functions to count zeros in a numpy array. In fact, you can use these functions to count values satisfying any given condition (for example, whether they are zero or not, or whether they are greater than some value or not, etc).
Note that using np.count_nonzero()
is simpler of the two methods. The following is the syntax to count zeros using this function –
# arr is a numpy array # count of zeros in arr n_zeros = np.count_nonzero(arr==0)
Let’s look at some examples of how to use the above functions. First, we will create a couple of numpy arrays that we will be using throughout this tutorial.
import numpy as np # one-dimensional array arr_1d = np.array([3, 0, 5, 2, 1, 0, 8, 6]) print(arr_1d) # two-dimensional array arr_2d = np.array([[4, 3, 0], [0, 0, 2], [2, 5, 6]]) print(arr_2d)
Output:
[3 0 5 2 1 0 8 6] [[4 3 0] [0 0 2] [2 5 6]]
Now we have a one-dimensional array and a two-dimensional array for which we will be counting the zeros.
Count all zeros in the array
To count all the zeros in an array, simply use the np.count_nonzero()
function checking for zeros. It returns the count of elements inside the array satisfying the condition (in this case, if it’s zero or not).
Let’s use this function to count the zeros in arr_1d
created above:
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
# count zeros in 1d array n_zeros = np.count_nonzero(arr_1d==0) # display the count of zeros print(n_zeros)
Output:
2
We get 2 as the output since there are two zero elements in the 1d array arr_1d
.
You can also use the same syntax to count zeros in higher dimensional arrays. Let’s count the number of zeros in arr_2d
using np.count_nonzero()
# count zeros in 2d array n_zeros = np.count_nonzero(arr_2d==0) # display the count of zeros print(n_zeros)
Output:
3
We get 3 as the output since there are three zero value elements in the array arr_2d
.
Count of zeros in each row
To count zeros in each row, pass axis=1
to the np.count_nonzero()
function. Let’s count zeros in each row of arr_2d
# count zeros in each row n_zeros = np.count_nonzero(arr_2d==0, axis=1) # display the count of zeros print(n_zeros)
Output:
[1 2 0]
It returns a numpy array of the count of zeros in each row. You can see that we have one zero-element in the first row, two in the second row, and no such elements in the third row.
Count of zeros in each column
To count zeros in each column, pass axis=0
to the np.count_nonzero()
function. Let’s count the zeros in each column of arr_2d
# count zeros in each column n_zeros = np.count_nonzero(arr_2d==0, axis=0) # display the count of zeros print(n_zeros)
Output:
[1 1 1]
We have one zero-element in each column of the array arr_2d
.
For more on the np.count_nonzero()
function, refer to its documentation.
Using np.where()
to count zeros in an array
Alternatively, you can use np.where()
to count the zeros in an array. np.where()
is generally used to find indexes of elements satisfying a condition in a numpy array.
You can use this function to find indexes of zero-valued elements in the array and then count them to get the count of zeros in the array. Let’s count the zeros in the array arr_1d
using this method:
# count zeros with np.where result = np.where(arr_1d==0) # show the result of np.where print(result) # count of zeros n_zeros = result[0].size # display the count of zeros print(n_zeros)
Output:
(array([1, 5], dtype=int64),) 2
You can see that np.where()
results in a tuple of numpy arrays showing the indexes satisfying the condition. We see that zeros are present at index 1 and 5 in the array arr_1
. To get the count, we use the .size
attribute of this index array.
You can also use np.where()
to count zeros in higher-dimensional arrays as well. For example, let’s use it to count zeros in arr_2d
# count zeros with np.where result = np.where(arr_2==0) # show the result of np.where print(result) # count of zeros n_zeros = result[0].size # display the count of zeros print(n_zeros)
Output:
(array([0, 1, 1], dtype=int64), array([2, 0, 1], dtype=int64)) 3
The returned value from np.where()
is a tuple of two arrays, the first one shows the row indexes of elements matching the condition (element equal to zero) and the second array gives the column indexes for those elements. Counting the indexes in any of these arrays gives the count of zeros in the array.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Tutorials on numpy arrays –
- How to sort a Numpy Array?
- Create Pandas DataFrame from a Numpy Array
- Different ways to Create NumPy Arrays
- Convert Numpy array to a List – With Examples
- Append Values to a Numpy Array
- Find Index of Element in Numpy Array
- Read CSV file as NumPy Array
- Filter a Numpy Array – With Examples
- Python – Randomly select value from a list
- Numpy – Sum of Values in Array
- Numpy – Elementwise sum of two arrays
- Numpy – Elementwise multiplication of two arrays
- Using the numpy linspace() method
- Using numpy vstack() to vertically stack arrays
- Numpy logspace() – Usage and Examples
- Using the numpy arange() method
- Using numpy hstack() to horizontally stack arrays
- Trim zeros from a numpy array in Python
- Get unique values and counts in a numpy array
- Horizontally split numpy array with hsplit()