Let’s learn how to calculate frequency of distinct values in Numpy array. We will use Numpy unique method to calculate that.
Numpy unique method
To calculate frequency of values use Numpy unique function. As arguments use your array and return_counts=True.
Then I created variable unique_values and using asarray function created new array with the values and corresponding frequencies.
import numpy as np my_array = np.array([1, 1, 2, 2, 2, 3, 3, 3, 4, 77]) unique, counts = np.unique(my_array, return_counts=True) unique_values = np.asarray((unique, counts)).T print(f"This is the frequency of values" f" in my array: \n {unique_values}")
Python printed out frequency of values. As you can see in my array I had 1, 2, 3, 4 and 77. In second column Python returned the number of these values.