I was working on a data analysis project where I needed to count the number of non-zero values in a NumPy array. I was looking for a quick and efficient way to do this without writing loops or complex logic. That’s when I discovered the np.count_nonzero() function in NumPy.
In this article, I’ll share how to use this useful function with practical examples from my experience. We’ll look at various ways to count non-zero elements in arrays of different dimensions and how to use conditions to count specific values.
So let’s get in!
np.count_nonzero()
np.count_nonzero() is a NumPy function that counts the number of non-zero elements in an array. It’s much faster than using Python loops, especially for large arrays.
The basic syntax is:
import numpy as np
np.count_nonzero(array, axis=None)Where:
arrayis the NumPy array you want to analyzeaxis(optional) specifies the axis along which to count non-zero elements
Read Copy Elements from One List to Another in Python
Count Non-Zero Elements using np.count_nonzero() in NumPy
Now, I will explain how to count non-zero elements using np.count_nonzero() in NumPy.
1. Basic Usage of np.count_nonzero()
Let’s start with a simple example to count non-zero elements in a 1D array in Python:
import numpy as np
# Create a sample array
arr = np.array([0, 1, 2, 0, 3, 0, 4])
# Count non-zero elements
count = np.count_nonzero(arr)
print(f"Number of non-zero elements: {count}") Output:
Number of non-zero elements: 4You can see the output in the screenshot below.

In this example, the function correctly identifies that there are 4 non-zero elements (1, 2, 3, and 4).
Check out Use np.argsort in Descending Order in Python
2. Count Along Specific Axes
When working with multi-dimensional arrays, you can count non-zero values along specific axes in Python:
import numpy as np
# Create a 2D array
arr_2d = np.array([
[0, 1, 0, 2],
[0, 0, 3, 0],
[4, 0, 5, 0]
])
# Count non-zero elements along rows (axis=1)
row_counts = np.count_nonzero(arr_2d, axis=1)
print("Non-zero counts per row:", row_counts)
# Count non-zero elements along columns (axis=0)
col_counts = np.count_nonzero(arr_2d, axis=0)
print("Non-zero counts per column:", col_counts)Output:
Non-zero counts per row: [2 1 2]
Non-zero counts per column: [1 1 2 1]You can see the output in the screenshot below.

This is particularly useful when analyzing data tables, where each row might represent a different record and columns represent features.
Read NumPy Filter 2D Array by Condition in Python
3. Use np.count_nonzero() with Conditions
One of the most useful features of count_nonzero() is that it can be used with conditions. This allows you to count elements that satisfy specific criteria:
import numpy as np
# Sample sales data for a US electronics store (units sold per quarter for 3 products)
sales = np.array([
[120, 150, 110, 160], # Product A
[90, 0, 85, 105], # Product B
[200, 210, 0, 190] # Product C
])
# Count quarters where sales exceeded 100 units for each product
high_sales_quarters = np.count_nonzero(sales > 100, axis=1)
print("Number of quarters with >100 units sold per product:", high_sales_quarters)
# Count products that had zero sales in at least one quarter
products_with_zero_sales = np.count_nonzero(np.count_nonzero(sales == 0, axis=1))
print("Number of products with zero sales in at least one quarter:", products_with_zero_sales)Output:
Number of quarters with >100 units sold per product: [4 1 3]
Number of products with zero sales in at least one quarter: 2You can see the output in the screenshot below.

This approach is extremely useful for data analysis tasks, like identifying months where sales dropped below targets or counting customers who meet specific criteria.
Read np.diff() Function in Python
Alternative Method: Use sum() with Boolean Arrays
While count_nonzero() is specifically designed for counting; you can achieve the same result using NumPy’s sum() function with Boolean arrays in Python:
import numpy as np
arr = np.array([0, 1, 2, 0, 3, 0, 4])
# Count non-zero elements using sum
count_sum = np.sum(arr != 0)
print(f"Number of non-zero elements: {count_sum}") # Output: 4This works because arr != 0 creates a boolean array, and when you sum a boolean array, True values are treated as 1 and False values as 0.
Check out Replace Values in NumPy Array by Index in Python
Use np.count_nonzero() with Missing Data
In real-world data analysis, you’ll often deal with missing values. NumPy represents missing values as np.nan. Let’s see how to handle them:
import numpy as np
# Array with missing values (NaN)
data = np.array([1.0, np.nan, 2.0, 0.0, np.nan, 3.0])
# Count non-zero, non-NaN elements
count = np.count_nonzero(~np.isnan(data) & (data != 0))
print(f"Number of non-zero, non-NaN elements: {count}") # Output: 3This is particularly useful when working with datasets that contain missing values, like customer surveys or scientific measurements.
Read np.add.at() Function in Python
Performance Considerations
One of the reasons I love using np.count_nonzero() is its performance. Let’s compare it with a Python loop approach:
import numpy as np
import time
# Create a large array
large_arr = np.random.randint(0, 2, size=10000000)
# Method 1: Using count_nonzero
start = time.time()
count1 = np.count_nonzero(large_arr)
end = time.time()
print(f"count_nonzero time: {end - start:.6f} seconds")
# Method 2: Using a Python loop
start = time.time()
count2 = sum(1 for x in large_arr if x != 0)
end = time.time()
print(f"Python loop time: {end - start:.6f} seconds")When I tested this on my machine, np.count_nonzero() was about 20 times faster than the loop-based approach, which makes a significant difference when working with large datasets.
Check out NumPy Array to a String in Python
np.count_nonzero() vs. np.count()
It’s important to note that there is no np.count() function in NumPy. The correct function is np.count_nonzero(). If you’re looking for a count() method, you might be thinking of the regular Python list.count() method, which counts occurrences of a specific value.
If you want to count specific values in a NumPy array, you can combine np.count_nonzero() with a condition:
import numpy as np
arr = np.array([1, 2, 3, 1, 2, 1, 4])
# Count occurrences of the value 1
count_ones = np.count_nonzero(arr == 1)
print(f"Number of ones: {count_ones}") # Output: 3I hope you found this guide on np.count_nonzero() helpful! This function has become one of my go-to tools for data analysis in Python. It’s simple, versatile, and incredibly efficient. Next time you need to count values in your NumPy arrays, give it a try instead of writing loops or complex logic.
If you’re working with numerical data in Python, mastering functions like np.count_nonzero() can significantly improve your code’s readability and performance. Happy coding!
Related tutorials you may read:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.