count_nonzero() is a fast, direct way to count elements satisfying a condition when combined with a comparison, since a boolean array's True values are treated as 1, nonzero, and False as 0 — counting how many elements exceed a threshold with count_nonzero(arr > 5) counts exactly how many elements exceed 5. It's generally clearer than the equivalent length of a filtered array, though summing a boolean array produces the identical count as a side effect of True behaving as 1 in arithmetic.
1Understanding np.count_nonzero()
count_nonzero() is a fast, direct way to count elements satisfying a condition when combined with a comparison, since a boolean array's True values are treated as 1, nonzero, and False as 0 — counting how many elements exceed a threshold with count_nonzero(arr > 5) counts exactly how many elements exceed 5. It's generally clearer than the equivalent length of a filtered array, though summing a boolean array produces the identical count as a side effect of True behaving as 1 in arithmetic.
count_nonzero(condition) is the idiomatic way to count how many elements satisfy a condition — equivalent to summing that same boolean condition, but its name makes the intent immediately clear to a reader without relying on the true-equals-1 trick.
import numpy as np
arr = np.array([0, 1, 0, 3, 0, 5])
print(np.count_nonzero(arr))2Practical Example
Here is a real-world application of np.count_nonzero() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([12, 45, 7, 23, 56, 3])
print(np.count_nonzero(arr > 20))3Best Practices
Follow these guidelines when working with np.count_nonzero():
1. Use count_nonzero(condition) to count elements matching a condition, since it reads more clearly than relying on sum()'s true-equals-1 behavior
2. Specify axis explicitly on multi-dimensional data to get per-row or per-column counts, rather than a single overall total
3. Prefer count_nonzero() over checking the length of a filtered array for counting matches, since it avoids constructing an intermediate filtered array just to measure its length
Tip: count_nonzero(condition) is the idiomatic way to count how many elements satisfy a condition — equivalent to summing that same boolean condition, but its name makes the intent immediately clear to a reader without relying on the true-equals-1 trick.
import numpy as np
arr = np.array([0, 1, 0, 3, 0, 5])
print(np.count_nonzero(arr))