Python Practice › NumPy Programs › Program 78

Frequency of unique values

EasyNumPy Programs · 78 of 100

Write a NumPy program to count how often each unique value appears.

Advertisement
Input
[8, 6, 7, 0, 7, 8, 6, 6]
Output
[[0 6 7 8]
 [1 3 2 2]]

Approach

  1. np.unique(..., return_counts=True).

Solution

Python
import numpy as npvalues, counts = np.unique([8, 6, 7, 0, 7, 8, 6, 6], return_counts=True)print(np.vstack((values, counts)))
Output
[[0 6 7 8]
 [1 3 2 2]]
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More numpy programs

← All 100 NumPy Programs