How to calculate statistical mode in Python
To calculate the mode of a statistical distribution in Python, you can use the mode() function of the statistics library.
mode(x)
The parameter x is a statistical distribution.
The mode () function outputs the distribution mode.
Note. To use the function you need to import it from the statistics module using the import or from import statement.
Examples
Example 1
To find the mode of the following distribution 1,3,5,6,6,6,7
>>> from statistics import mode
>>> data=[1,3,5,6,6,6,7]
>>> mode(data)
The distribution contains numeric values
The result of the mode() function is
6
The value 6 is the mode of the distribution because it occurs three times, more than the other values.
Example 2
To find the mode of the following red, green, red, yellow, blue distribution
>>> from statistics import mode
>>> data=["red", "green", "red", "yellow", "blue"]
>>> mode(data)
In this case the distribution contains nominal (not numeric) information.
The mode () function returns as output
red
The color red is the mode of distribution because it occurs twice, while the colors green, yellow and blue only once.
Note. If the distribution has no single modal value, the mode () function returns a message error 'no unique mode; found %d equally common values'. You need to catch the error with an exception.