Find Unique Values with NumPy
Unique-value counts are useful for categorical summaries, frequency tables, and validating encoded data.
What is Find Unique Values with NumPy?
Unique-value counts are useful for categorical summaries, frequency tables, and validating encoded data.
Find unique array values and their occurrence counts with NumPy.
When should you use it?
- Perform numerical operations on many values at once.
- Process arrays, matrices, and scientific data efficiently.
- Prepare data for data science and machine learning.
Example code
main.py
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, counts)))
Expected output
{1: 2, 2: 1, 3: 3}
How it works
Unique sorts the distinct values and return_counts supplies a matching count for each one.
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.