Numpy count_nonzero method - Python
Last Updated :
20 Sep, 2025
When working with arrays, sometimes you need to quickly count how many elements are not equal to zero. NumPy makes this super easy with the numpy.count_nonzero() function.
This is useful when:
- You want to count valid entries in datasets.
- You’re filtering out missing (zero) values.
- You need quick statistics on arrays.
Example: Let’s start with the simplest example to understand how it works.
Python
import numpy as np
arr = [0, 1, 0, 2, 3]
result = np.count_nonzero(arr)
print(result)
Explanation: array is [0, 1, 0, 2, 3] and non-zero elements are 1, 2, 3 -> total 3 values.
Syntax
numpy.count_nonzero(arr, axis=None)
Parameters:
- arr: array_like - Input array.
- axis: int or tuple, optional - None counts over the whole array; int/tuple counts along given axis (row/column).
Return Value: int (if axis=None) or array of ints (if axis is given). Represents the count of non-zero elements.
Examples
Example 1: In this example, we count all non-zero elements in a 2D array.
Python
import numpy as np
arr = [[0, 1, 2, 3, 0],
[0, 5, 6, 0, 7]]
result = np.count_nonzero(arr)
print(result)
Explanation: There are 6 values that are not zero.
Example 2: Here, we count non-zero elements column-wise using axis=0.
Python
import numpy as np
arr = [[0, 1, 2, 3, 4],
[5, 0, 6, 0, 7]]
result = np.count_nonzero(arr, axis=0)
print(result)
Explanation:
- Column 0 -> 1 non-zero (5) and Column 1 -> 1 non-zero (1)
- Column 2 -> 2 non-zeros (2, 6), Column 3 -> 1 non-zero (3) and Column 4 -> 2 non-zeros (4, 7)
Example 3: This example counts non-zero elements row-wise using axis=1.
Python
import numpy as np
arr = [[0, 0, 0, 3, 4],
[5, 6, 0, 0, 7]]
result = np.count_nonzero(arr, axis=1)
print(result)
Explanation: Row 0 -> 2 non-zeros (3, 4) and Row 1 -> 3 non-zeros (5, 6, 7)
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice