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 values in NumPy
Introduction
When you want to know all the different colors used in a photo's pixel data.
When you have survey answers and want to see all the unique responses.
When cleaning data to find and remove duplicate entries.
When counting how many different categories appear in a dataset.
Syntax
NumPy
numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
ar is the input array or list.
You can ask for extra info like where the unique values came from or how many times they appear by setting return_index, return_inverse, or return_counts to True.
Examples
This finds unique values in a simple list and prints them sorted.
NumPy
import numpy as np arr = [1, 2, 2, 3, 4, 4, 4] unique_values = np.unique(arr) print(unique_values)
This finds unique values and how many times each appears.
NumPy
arr = np.array([5, 3, 5, 2, 3]) unique_vals, counts = np.unique(arr, return_counts=True) print(unique_vals) print(counts)
This finds unique rows in a 2D array.
NumPy
arr = np.array([[1, 2], [2, 3]]) unique_axis0 = np.unique(arr, axis=0) print(unique_axis0)
Sample Program
This program shows how to get unique values from an array and also count how many times each unique value appears.
NumPy
import numpy as np # Sample data with repeated values data = np.array([10, 20, 20, 30, 10, 40, 50, 50, 50]) # Find unique values unique_vals = np.unique(data) print("Unique values:", unique_vals) # Find unique values and their counts unique_vals, counts = np.unique(data, return_counts=True) print("Counts of each unique value:", counts)
OutputSuccess
Important Notes
np.unique() always returns sorted unique values.
Use return_counts=True to see how often each unique value appears.
For multi-dimensional arrays, use the axis parameter to find unique rows or columns.
Summary
np.unique() helps find all different values in data.
You can get extra info like counts or original positions.
It works on lists and arrays, including multi-dimensional ones.