Unique elements
EasyNumPy Programs · 55 of 100
Write a NumPy program to get the unique elements of an array.
Input[25, 33, 10, 45, 33, 10]
Output[10 25 33 45]
[25 33 10 45]
Approach
np.unique returns them sorted; use the index to keep first-seen order.
Solution
Python
import numpy as npa = np.array([25, 33, 10, 45, 33, 10])print(np.unique(a))_, first = np.unique(a, return_index=True)print(a[np.sort(first)])
Output
[10 25 33 45]
[25 33 10 45]
Line by line
Lines 4-5return_index gives each value’s first position; sorting those keeps the original order.
Learn the concept
New to this topic? Read the lesson, then come back.
More numpy programs
← All 100 NumPy Programs