← Back to NumPy Course | Chapter 8: Statistics | Lesson 5 of 6

np.unique()

np.unique() finds the distinct values in an array, sorted, and can also count them.

In this page:

  1. np.unique()
Syntax
python
values = np.unique(arr)
values, counts = np.unique(arr, return_counts=True)

np.unique()

np.unique returns the sorted unique elements. With return_counts=True you also get how many times each appears, and return_inverse maps each original element to its unique index. It flattens multi-dimensional input unless you give an axis.

Note: unique with return_counts is a fast frequency table.

Example: np.unique()

python
import numpy as np

a = np.array([3, 1, 2, 3, 3, 1])
vals, counts = np.unique(a, return_counts=True)
print(vals)
print(counts)

# Output:
# [1 2 3]
# [2 1 3]
Related Topics
Common Mistakes
  1. Expecting the original order to be preserved
  2. Forgetting multi-dimensional input is flattened
  3. Not asking for counts when needed
Chapter Summary
  • unique returns sorted distinct values
  • return_counts gives frequencies
  • Original order is not kept
  • Flattens unless axis is given
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.