How do you count occurrences of a specific value inside a NumPy ndarray? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you count occurrences of a specific value inside a NumPy ndarray?

message-square
0

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 == target creates 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 an axis= or on large multi-dimensional arrays.
    • Note: In NumPy 2.0+, np.count_nonzero(mask) returns a Python int (whereas (mask).sum() returns a np.int64 scalar).
  • Counting NaN values (np.isnan(arr) instead of arr == np.nan):
    • Because np.nan == np.nan always evaluates to False per IEEE 754 floating-point rules, np.count_nonzero(arr == np.nan) always returns 0. Always use np.count_nonzero(np.isnan(arr)) to count NaNs.
  • 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). Use np.count_nonzero(np.isclose(arr, 0.3)) when matching floats.
  • Never call Python’s list.count() or collections.Counter on multi-dimensional arrays:
    • ndarray has no .count() method (AttributeError), list(arr).count(x) fails on 2D+ arrays with ValueError: The truth value of an array with more than one element is ambiguous, and Counter(arr.flat) runs a slow Python loop that is 20x–100x slower than np.count_nonzero().
  • Ultra-fast frequency counts for non-negative integers (np.bincount):
    • When arr is 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 with target < len(counts) if target might exceed arr.max()).

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.