The Python statistics module has a number of useful functions to calculate the mode, such as mode() and multimode(). Lets write some code snippets and understand how to use the mode function in Python statistics module.
Calculating mode value of given data
The mode value of a given data set is the value which occurs the most. Mode can be calculated by counting the frequency of each value. The value with the highest frequency is the mode. There are 2 functions available to calculate the mode.
- mode() function
- multimode() function
Using the mode() function
The mode() function calculates the mode value of a given list of numbers. Mode is calculated by counting the frequency of each value. The value with the highest frequency is the mode. If there are two or more values with the same highest frequency, then the first encountered value is returned as the mode. The below code snippet explains the usage and syntax of mode() function.
# using the mode() function on a given list of numbers
import statistics
numbers1 = [10, 20, 30, 20, 40] #Scenario 1, single mode
mode1 = statistics.mode(numbers1)
print("The given numbers are ", numbers1)
print("The mode value is ", mode1) # returns 20
numbers2 = [10, 20, 30, 40, 30, 40] #Scenario 2, multiple modes
mode2 = statistics.mode(numbers2)
print("The given numbers are ", numbers2)
print("The mode value is ", mode2) # returns 30 [30 occurs before 40]
Using the multimode() function
The multimode() function is similar to the mode() function. The function however returns a list of mode values in case there are 2 or more values with same highest frequency.
# using the multimode() function on a given list of numbers
import statistics
numbers1 = [10, 20, 30, 20, 40] #Scenario 1, single mode
mode1 = statistics.multimode(numbers1)
print("The given numbers are ", numbers1)
print("The mode value is ", mode1) # returns [20]
numbers2 = [10, 20, 30, 40, 30, 40] #Scenario 2, multiple modes
mode2 = statistics.multimode(numbers2)
print("The given numbers are ", numbers2)
print("The mode value is ", mode2) # returns [30, 40]