Find Unique Values and Counts with NumPy
Get the distinct values of an array and how often each appears with one call to np.unique.
- np.unique for distinct values
- return_counts=True
- Turning the result into a dictionary
12 times21 time33 timesDistinct values and their counts
The problem
Which categories appear in a dataset, and how often? Survey answers, product codes and labels all need a quick frequency table before analysis, and to check for typos or unexpected values.
Think of it like this
Finding unique values with counts is like sorting a bag of colored beads into cups. Each cup holds one color, and you write the number of beads on each cup. The cups are arranged in order.
np.unique(values, ...)🥣 One cup per distinct value, in sorted orderreturn_counts=True🔢 Write how many beads are in each cup.tolist()🧾 Convert to plain Python numbersdict(zip(...))📋 {1: 2, 2: 1, 3: 3}np.unique returns the distinct values of an array in sorted order, and with return_counts=True also how many times each value appears.
Key points
np.unique(values, return_counts=True)returns two arrays:uniqueandcounts.uniqueholds the distinct values sorted: 1, 2, 3.countsholds how often each one appears: 2, 1, 3.unique.tolist()andcounts.tolist()turn NumPy numbers into plain Python numbers, so the dictionary prints as{1: 2, 2: 1, 3: 3}.
When should you use it?
- Frequency tables for categories and labels.
- Checking data for unexpected or misspelled values.
- Counting class sizes before training a model.
When not to use it
- Plain Python lists:
collections.Countergives counts without NumPy. - Tables with several columns: pandas
value_counts()keeps labels and sorts by count.
Example code
import numpy as np
values = np.array([3, 1, 3, 2, 1, 3])
unique, counts = np.unique(values, return_counts=True)
print(dict(zip(unique.tolist(), counts.tolist())))
Result of running the code
{1: 2, 2: 1, 3: 3}
Code explanation
np.unique sorts the distinct values of values and, because of return_counts=True, also returns how many times each one appears. The two results are unpacked into unique and counts. tolist() converts both into ordinary Python lists, so zip pairs plain numbers and the dictionary prints as {1: 2, 2: 1, 3: 3} instead of showing NumPy number types.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input shape and dtype.
- Try negative, floating-point, and missing values.
- Apply the operation to larger multidimensional arrays and measure performance.
Common mistakes
Printing NumPy numbers in a dictionary
In NumPy 2 the keys and values print as np.int64(1) instead of 1.
print(dict(zip(unique, counts)))
print(dict(zip(unique.tolist(), counts.tolist())))
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Word Tokenizer and Vocabulary Split text into lowercase words and build a vocabulary sorted by frequency, the first step of any language model. Easy
- Remove Duplicates Keep only the first occurrence of each value. Easy