🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEnumpy

numpy Documentation

LOADING ENGINE...

np.count_nonzero()

AI & DATA SCIENCE // np-count-nonzero

np.count_nonzero() counts the number of non-zero elements in an array, either overall or along a specified axis.

Syntax

np.count_nonzero(arr, axis=None)

Deep Dive Course

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.

editor.html
import numpy as np

arr = np.array([0, 1, 0, 3, 0, 5])
print(np.count_nonzero(arr))
localhost:3000

2Practical Example

Here is a real-world application of np.count_nonzero() showing how it is used in production NumPy code.

editor.html
import numpy as np

arr = np.array([12, 45, 7, 23, 56, 3])
print(np.count_nonzero(arr > 20))
localhost:3000

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.

editor.html
import numpy as np

arr = np.array([0, 1, 0, 3, 0, 5])
print(np.count_nonzero(arr))
localhost:3000

Examples

Example 01Basic Usage
import numpy as np

arr = np.array([0, 1, 0, 3, 0, 5])
print(np.count_nonzero(arr))
Example 02Advanced Example
import numpy as np

arr = np.array([12, 45, 7, 23, 56, 3])
print(np.count_nonzero(arr > 20))

Best Practices

  • Use count_nonzero(condition) to count elements matching a condition, since it reads more clearly than relying on sum()'s true-equals-1 behavior
  • Specify axis explicitly on multi-dimensional data to get per-row or per-column counts, rather than a single overall total
  • 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

Interview Question

Why does np.count_nonzero(arr > 5) give the same result as summing the boolean array arr > 5, and which is generally preferred?

Hint: Think about how a boolean array behaves numerically.

A comparison like arr > 5 produces a boolean array, and booleans in NumPy behave as integers in arithmetic contexts, True acting as 1 and False as 0 — so summing a boolean array effectively counts how many elements were True, and count_nonzero() counts exactly the same thing by definition, checking which elements are nonzero, which for a boolean array means checking which are True. Both give identical results, but count_nonzero() is generally preferred for readability, since its name directly states the intent of counting matches, rather than relying on a reader recognizing the true-equals-1 arithmetic trick behind summing.

Exercises

MediumPractice using np.count_nonzero() in a real scenario.
View Solution
import numpy as np

arr = np.array([0, 1, 0, 3, 0, 5])
print(np.count_nonzero(arr))

Frequently Asked Questions

Why does np.count_nonzero(arr > 5) give the same result as summing the boolean array arr > 5, and which is generally preferred?

A comparison like arr > 5 produces a boolean array, and booleans in NumPy behave as integers in arithmetic contexts, True acting as 1 and False as 0 — so summing a boolean array effectively counts how many elements were True, and count_nonzero() counts exactly the same thing by definition, checking which elements are nonzero, which for a boolean array means checking which are True. Both give identical results, but count_nonzero() is generally preferred for readability, since its name directly states the intent of counting matches, rather than relying on a reader recognizing the true-equals-1 arithmetic trick behind summing.

Related Functions

np-argwhereboolean-indexingnp-sum