Home » How to Find Most Frequent Value in NumPy Array (With Examples)

How to Find Most Frequent Value in NumPy Array (With Examples)

by Erma Khan

You can use the following methods to find the most frequent value in a NumPy array:

Method 1: Find Most Frequent Value

#find frequency of each value
values, counts = np.unique(my_array, return_counts=True)

#display value with highest frequency
values[counts.argmax()]

If there are multiple values that occur most frequently in the NumPy array, this method will only return the first value.

Method 2: Find Each Most Frequent Value

#find frequency of each value
values, counts = np.unique(my_array, return_counts=True)

#display all values with highest frequencies
values[counts == counts.max()]

If there are multiple values that occur most frequently in the NumPy array, this method will return each of the most frequently occurring values.

The following examples show how to use each method in practice.

Example 1: Find Most Frequent Value in NumPy Array

Suppose we have the following NumPy array:

import numpy as np

#create NumPy array
my_array = np.array([1, 2, 4, 4, 4, 5, 6, 7, 12])

Notice that there is only one value that occurs most frequently in this array: 4.

We can use the argmax() function to return the value that occurs most frequently in the array:

#find frequency of each value
values, counts = np.unique(my_array, return_counts=True)

#display value with highest frequency
values[counts.argmax()]

4

The function correctly returns the value 4.

Example 2: Find Each Most Frequent Value in NumPy Array

Suppose we have the following NumPy array:

import numpy as np

#create NumPy array
my_array = np.array([1, 2, 4, 4, 4, 5, 6, 7, 12, 12, 12])

Notice that there are two values that occur most frequently in this array: 4 and 12.

We can use the max() function to return each of the values that occur most frequently in the array:

#find frequency of each value
values, counts = np.unique(my_array, return_counts=True)

#display each value with highest frequency
values[counts == counts.max()]

array([ 4, 12])

The function correctly returns the values 4 and 12.

Note: You can find the complete documentation for the NumPy unique() function here.

Additional Resources

The following tutorials explain how to perform other common tasks in NumPy:

How to Remove Duplicate Elements in NumPy Array
How to Replace Elements in NumPy Array
How to Rank Items in NumPy Array

Related Posts