How to Calculate the Mode of NumPy Array (With Examples)


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.

Additional Resources

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

How to Map a Function Over a NumPy Array
How to Find Index of Value in NumPy Array
How to Calculate the Magnitude of a Vector Using NumPy

Leave a Reply

Your email address will not be published.