Use np.count_nonzero(arr == target) (or int((arr == target).sum())) to count how many elements in a NumPy ndarray equal target across the entire array in fast vectorized C code, passing axis=0 or axis=1 when you need per-column or per-row occurrence counts instead of a single scalar total.
Basic Example
import numpy as np
arr = np.array([
[1, 3, 2, 3],
[3, 0, 3, 1],
[2, 3, 1, 0],
])
# 1. Recommended: Count total occurrences of `3` across the entire array
count_3 = np.count_nonzero(arr == 3)
print(count_3)
# Output: 5
# 2. Count occurrences along a specific axis (per column or per row):
per_column = np.count_nonzero(arr == 3, axis=0)
per_row = np.count_nonzero(arr == 3, axis=1)
print("Per column:", per_column) # Output: [1 2 1 1]
print("Per row: ", per_row) # Output: [2 2 1]
# 3. Count ALL unique values and their frequencies at once:
values, counts = np.unique(arr, return_counts=True)
print(dict(zip(values.tolist(), counts.tolist())))
# Output: {0: 2, 1: 3, 2: 2, 3: 5}
Key Details & Edge Cases
- Why
np.count_nonzero(arr == target)is faster than(arr == target).sum():arr == targetcreates a boolean mask (dtype=bool).np.count_nonzero()iterates directly over the boolean bytes in C without promoting booleans to 64-bit integers (int64), making it noticeably faster—especially when counting along anaxis=or on large multi-dimensional arrays.- Note: In NumPy 2.0+,
np.count_nonzero(mask)returns a Pythonint(whereas(mask).sum()returns anp.int64scalar).
- Counting
NaNvalues (np.isnan(arr)instead ofarr == np.nan):- Because
np.nan == np.nanalways evaluates toFalseper IEEE 754 floating-point rules,np.count_nonzero(arr == np.nan)always returns0. Always usenp.count_nonzero(np.isnan(arr))to countNaNs.
- Because
- Counting floating-point numbers within tolerance (
np.isclose):- Exact equality (
arr == 0.3) often misses values affected by floating-point rounding (0.1 + 0.2 == 0.30000000000000004). Usenp.count_nonzero(np.isclose(arr, 0.3))when matching floats.
- Exact equality (
- Never call Python’s
list.count()orcollections.Counteron multi-dimensional arrays:ndarrayhas no.count()method (AttributeError),list(arr).count(x)fails on 2D+ arrays withValueError: The truth value of an array with more than one element is ambiguous, andCounter(arr.flat)runs a slow Python loop that is 20x–100x slower thannp.count_nonzero().
- Ultra-fast frequency counts for non-negative integers (
np.bincount):- When
arris a 1D array of non-negative integers (0, 1, 2, ...),np.bincount(arr)[target]counts occurrences in $O(n)$ without allocating a boolean mask (guard withtarget < len(counts)iftargetmight exceedarr.max()).
- When
Comparison of Occurrence-Counting Methods in NumPy
| Method | Works on Any dtype & Dimension? |
Supports axis= Breakdown? |
Return Type | Best Used When |
|---|---|---|---|---|
np.count_nonzero(arr == val) (Recommended) |
Yes (ints, floats, strings, booleans, N-D) | Yes (axis=0, axis=1, etc.) |
int (scalar) or ndarray (with axis=) |
Counting occurrences of a single known value (or condition like arr > 5 / np.isnan(arr)). |
(arr == val).sum() |
Yes | Yes (axis=0, axis=1, etc.) |
np.int64 scalar or ndarray |
Inline expressions where you already have a boolean mask and want a NumPy integer scalar. |
np.unique(arr, return_counts=True) |
Yes (flattens by default; axis= supported) |
Yes | Tuple of (unique_vals, counts) |
Building a complete frequency table for all distinct values in the array at once. |
np.bincount(arr.ravel())[val] |
No (1D non-negative integers only) | No (1D only) | np.intp |
Maximum-speed counting on dense, non-negative integer IDs or class labels. |
You must log in or register to comment.
