w3resource logo
Python Exercises

Python NumPy: Count the frequency of unique values in numpy array

Python NumPy: Array Object Exercise-94 with Solution

Write a Python program to count the frequency of unique values in numpy array.

Sample Solution:-

Python Code:

import numpy as np
a = np.array( [10,10,20,10,20,20,20,30, 30,50,40,40] )
print("Original array:")
print(a)
unique_elements, counts_elements = np.unique(a, return_counts=True)
print("Frequency of unique values of the said array:")
print(np.asarray((unique_elements, counts_elements)))

Sample Output:

Original array:                                                        
[10 10 20 10 20 20 20 30 30 50 40 40]                                  
Frequency of unique values of the said array:                          
[[10 20 30 40 50]                                                      
 [ 3  4  2  2  1]]

Python Code Editor:

import numpy as np
a = np.array( [10,10,20,10,20,20,20,30, 30,50,40,40] )
print("Original array:")
print(a)
unique_elements, counts_elements = np.unique(a, return_counts=True)
print("Frequency of unique values of the said array:")
print(np.asarray((unique_elements, counts_elements)))

Improve this sample solution and post your code through Disqus