You are currently viewing How to count the frequency of unique values using np.unique()

How to count the frequency of unique values using np.unique()

In python, the unique values that exist in the array can easily find out using numpy.unique() function.

In python, the unique values that exist in the array can easily find out using numpy.unique() function.

Syntax

numpy.unique(arrayreturn_index=Falsereturn_inverse=Falsereturn_counts=Falseaxis=None)

Example 1

import numpy as np

x = np.array([1,1,1,2,2,2,5,25,1,1,2,3,4,2,3,2,3,2,31,3,2,31,2,32,3,3,3,3,3,3,34,4,4,45,5,5,5,5,5])

unique, counts = np.unique(x, return_counts=True)

print(np.asarray((unique, counts)).T)

Output

>> print(np.asarray((unique, counts)).T)

[[ 1  5]
 [ 2  9]
 [ 3 10]
 [ 4  3]
 [ 5  6]
 [25  1]
 [31  2]
 [32  1]
 [34  1]
 [45  1]]


>> print(np.asarray((unique, counts)))

[[ 1  2  3  4  5 25 31 32 34 45]
 [ 5  9 10  3  6  1  2  1  1  1]]

Example 2

import numpy as np

y = np.array(['red', 'green', 'blue', 'green', 'orange', 'blue', 'red'])
unique, counts = np.unique(y, return_counts=True)

print(np.asarray((unique, counts)).T)

Output

>> print(np.asarray((unique, counts)).T)


[['blue' '2']
 ['green' '2']
 ['orange' '1']
 ['red' '2']]

Leave a Reply