ndarray
count items
Python
NumPy
data analysis

How do I count the occurrence of a certain item in an ndarray?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In NumPy, counting how many times a value appears in an ndarray is usually a one-line operation. The standard pattern is to build a boolean mask and then count the True values, which is both readable and fast because the work stays inside NumPy's vectorized operations.

Count One Exact Value

The most direct way to count a single item is:

python
1import numpy as np
2
3arr = np.array([[1, 2, 1], [3, 1, 4]])
4target = 1
5
6count = np.count_nonzero(arr == target)
7print(count)

arr == target produces a boolean array of the same shape. Every matching element becomes True. np.count_nonzero then counts those True values.

You will also see:

python
count = np.sum(arr == target)

That works because True behaves like 1 and False behaves like 0, but count_nonzero expresses the intent more clearly.

Count by Row or by Column

Sometimes you want more than a single total. You may need to know how often a value appears in each row or in each column. The same mask can be counted along a chosen axis.

python
1import numpy as np
2
3arr = np.array([
4    [1, 2, 1, 5],
5    [3, 1, 4, 1],
6    [1, 1, 2, 2],
7])
8
9mask = arr == 1
10
11row_counts = np.count_nonzero(mask, axis=1)
12col_counts = np.count_nonzero(mask, axis=0)
13
14print("row counts:", row_counts)
15print("column counts:", col_counts)

This is useful in matrix analysis, image processing, and data-cleaning tasks where the position of matches matters.

Count All Unique Values at Once

If you need a frequency table for every distinct item, do not loop through targets manually. Use np.unique with return_counts=True.

python
1import numpy as np
2
3arr = np.array([2, 1, 2, 3, 3, 3, 4, 1, 2])
4
5values, counts = np.unique(arr, return_counts=True)
6
7for value, count in zip(values, counts):
8    print(value, count)

That approach is usually the best fit for summaries, histograms of categorical data, or quick exploratory checks.

For dense non-negative integers, np.bincount can also be very efficient:

python
1import numpy as np
2
3arr = np.array([0, 2, 2, 1, 0, 2, 3])
4counts = np.bincount(arr)
5print(counts)

Here counts[2] is the number of times the value 2 appears.

Count Values Matching a Condition

The exact same pattern works for conditions, not just equality. This is one reason the mask approach is so powerful.

python
1import numpy as np
2
3arr = np.array([5, 12, 7, 18, 3, 21])
4
5count_gt_10 = np.count_nonzero(arr > 10)
6count_in_range = np.count_nonzero((arr >= 5) & (arr <= 15))
7
8print(count_gt_10)
9print(count_in_range)

You are still counting True values, but now the boolean mask is created from a comparison expression instead of an exact match.

Special Cases: Floating Point Values and NaN

Floating-point arrays need extra care because direct equality is sometimes too strict. Two values that look identical when printed may differ slightly in binary representation.

Use np.isclose when approximate equality is what you actually want:

python
1import numpy as np
2
3arr = np.array([0.1 + 0.2, 0.3, 0.3000001, 0.31])
4count = np.count_nonzero(np.isclose(arr, 0.3, rtol=1e-5, atol=1e-8))
5
6print(count)

NaN is another special case because NaN != NaN. That means direct comparison will never count missing values correctly.

python
1import numpy as np
2
3arr = np.array([1.0, np.nan, np.nan, 2.0])
4count_nan = np.count_nonzero(np.isnan(arr))
5
6print(count_nan)

Whenever the target is missing data, use np.isnan rather than == np.nan.

Common Pitfalls

  • Writing a Python loop over every element instead of using a vectorized mask.
  • Forgetting the axis argument and getting one global total instead of row-wise or column-wise counts.
  • Using direct equality for floating-point values that should be compared approximately.
  • Trying to count NaN with == np.nan instead of np.isnan.
  • Using np.bincount on negative values or non-integer data, where it does not apply.

Summary

  • Use np.count_nonzero(arr == target) to count one exact value in an ndarray.
  • Add axis=0 or axis=1 when you need counts by column or by row.
  • Use np.unique(..., return_counts=True) for a full frequency table.
  • Use np.isclose for approximate floating-point comparisons.
  • Use np.isnan when the item you need to count is missing-value data.

Course illustration
Course illustration

All Rights Reserved.