How can I calculate the Mode of NumPy Array?

The mode of a NumPy array can be calculated using the scipy.stats.mode() function. This function takes in an array and returns an array of the mode values for each column. The mode of an array is the most commonly occurring value in that array. This calculation can be useful for analyzing data sets and identifying patterns in data.


You can use the following basic syntax to find the mode of a NumPy array:

#find unique values in array along with their counts
vals, counts = np.unique(array_name, return_counts=True)

#find mode
mode_value = np.argwhere(counts == np.max(counts))

Recall that the mode is the value that occurs most often in an array.

Note that it’s possible for an array to have one mode or multiple modes.

The following examples show how to use this syntax in practice.

Example 1: Calculating Mode of NumPy Array with Only One Mode

The following code shows how to find the mode of a NumPy array in which there is only one mode:

import numpy as np

#create NumPy array of values with only one mode
x = np.array([2, 2, 2, 3, 4, 4, 5, 5, 5, 5, 7])

#find unique values in array along with their counts
vals, counts = np.unique(x, return_counts=True)

#find mode
mode_value = np.argwhere(counts == np.max(counts))

#print list of modes
print(vals[mode_value].flatten().tolist())

[5]

#find how often mode occurs
print(np.max(counts))

4

From the output we can see that the mode is 5 and it occurs 4 times in the NumPy array.

Example 2: Calculating Mode of NumPy Array with Multiple Modes

The following code shows how to find the mode of a NumPy array in which there are multiple modes:

import numpy as np

#create NumPy array of values with multiple modes
x = np.array([2, 2, 2, 3, 4, 4, 4, 5, 5, 5, 7])

#find unique values in array along with their counts
vals, counts = np.unique(x, return_counts=True)

#find mode
mode_value = np.argwhere(counts == np.max(counts))

#print list of modes
print(vals[mode_value].flatten().tolist())

[2, 4, 5]

#find how often mode occurs
print(np.max(counts))

3

From the output we can see that this NumPy array has three modes: 2, 4, and 5.

We can also see that each of these values occurs 3 times in the array.

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

x