0
0
NumPydata~5 mins

np.count_nonzero() for counting in NumPy

Choose your learning style9 modes available
Introduction

We use np.count_nonzero() to quickly count how many values in data are not zero. It helps us find important information fast.

Counting how many students passed an exam (non-zero scores).
Finding how many sensors detected movement (non-zero readings).
Checking how many days had sales in a store (non-zero sales).
Counting how many pixels in an image are bright (non-zero brightness).
Syntax
NumPy
np.count_nonzero(a, axis=None, keepdims=False)

a is the input array where you want to count non-zero values.

axis lets you count along rows, columns, or the whole array.

Examples
Counts all non-zero numbers in a simple list.
NumPy
np.count_nonzero([1, 0, 2, 0, 3])
Counts non-zero values in each column of a 2D array.
NumPy
np.count_nonzero([[0, 1], [2, 0]], axis=0)
Counts non-zero values in each row of a 2D array.
NumPy
np.count_nonzero([[0, 1], [2, 0]], axis=1)
Sample Program

This program counts how many sales are non-zero in total, per day, and per product using np.count_nonzero().

NumPy
import numpy as np

# Create a 2D array representing sales for 3 days and 4 products
sales = np.array([[0, 5, 0, 3],
                  [2, 0, 0, 0],
                  [0, 0, 1, 4]])

# Count total non-zero sales
total_nonzero = np.count_nonzero(sales)

# Count non-zero sales per day (row)
nonzero_per_day = np.count_nonzero(sales, axis=1)

# Count non-zero sales per product (column)
nonzero_per_product = np.count_nonzero(sales, axis=0)

print(f"Total non-zero sales: {total_nonzero}")
print(f"Non-zero sales per day: {nonzero_per_day}")
print(f"Non-zero sales per product: {nonzero_per_product}")
OutputSuccess
Important Notes

Zero means 'no data' or 'no event' in many cases, so counting non-zero helps find actual occurrences.

You can use axis to count along rows or columns for more detailed analysis.

Summary

np.count_nonzero() counts how many values are not zero in data.

It works on arrays of any shape and can count overall or by rows/columns.

This function is useful to quickly find how many events or values exist in your data.