We use np.unique() to find all the different values in a list or array. It helps us see what unique items are there without repeats.
0
0
np.unique() for unique elements in NumPy
Introduction
You want to know all the different colors used in a photo's pixel data.
You have survey answers and want to list all distinct responses.
You want to remove duplicate numbers from a list of measurements.
You need to count how many unique products were sold in a store.
You want to find unique words in a text converted to an array.
Syntax
NumPy
np.unique(array, return_index=False, return_inverse=False, return_counts=False, axis=None)
array is the input list or array you want to check.
Optional arguments let you get extra info like where each unique item first appears (return_index) or how many times each appears (return_counts).
Examples
This finds unique numbers in the array and prints them sorted.
NumPy
import numpy as np arr = np.array([1, 2, 2, 3, 4, 4, 4]) unique_values = np.unique(arr) print(unique_values)
This also counts how many times each unique number appears.
NumPy
unique_vals, counts = np.unique(arr, return_counts=True) print(unique_vals) print(counts)
This finds unique rows in a 2D array.
NumPy
arr2d = np.array([[1, 2], [2, 3]]) unique_rows = np.unique(arr2d, axis=0) print(unique_rows)
Sample Program
This program shows how to find unique numbers in a list and count how many times each appears.
NumPy
import numpy as np # Create an array with repeated numbers numbers = np.array([5, 3, 5, 2, 3, 8, 9, 2, 8]) # Find unique numbers unique_numbers = np.unique(numbers) print('Unique numbers:', unique_numbers) # Find unique numbers and their counts unique_vals, counts = np.unique(numbers, return_counts=True) print('Counts of each unique number:') for val, count in zip(unique_vals, counts): print(f'{val} appears {count} times')
OutputSuccess
Important Notes
np.unique() returns sorted unique values by default.
Use return_counts=True to see how often each unique value appears.
For 2D arrays, use axis=0 or axis=1 to find unique rows or columns.
Summary
np.unique() helps find all different values in data.
It can also tell you how many times each unique value appears.
Works with 1D and 2D arrays, and sorts the results automatically.