Mode in Python – Most Common Value in List & DataFrame (2 Examples)
In this tutorial you’ll learn how to calculate the mode in a list or a pandas DataFrame column in the Python programming language.
Example 1: Calculating the Mode of a List Object
my_lt = [10, 6, 2, 2, 15, 20, 3, 7, 4] # Constructing a list in Python print(my_lt) # [10, 6, 2, 2, 15, 20, 3, 7, 4] |
my_lt = [10, 6, 2, 2, 15, 20, 3, 7, 4] # Constructing a list in Python print(my_lt) # [10, 6, 2, 2, 15, 20, 3, 7, 4]
import statistics # Load statistics |
import statistics # Load statistics
print(statistics.mode(my_lt)) # Computing the mode of a list # 2 |
print(statistics.mode(my_lt)) # Computing the mode of a list # 2
Example 2: Calculating the Mode of the Columns in a pandas DataFrame
import pandas as pd # Load pandas |
import pandas as pd # Load pandas
my_df = pd.DataFrame({'A':[6, 1, 8, 1, 3, 8, 1], # Constructing a pandas DataFrame 'B':[6, 1, 8, 5, 3, 8, 9]}) print(my_df) # A B # 0 6 6 # 1 1 1 # 2 8 8 # 3 1 5 # 4 3 3 # 5 8 8 # 6 1 9 |
my_df = pd.DataFrame({'A':[6, 1, 8, 1, 3, 8, 1], # Constructing a pandas DataFrame 'B':[6, 1, 8, 5, 3, 8, 9]}) print(my_df) # A B # 0 6 6 # 1 1 1 # 2 8 8 # 3 1 5 # 4 3 3 # 5 8 8 # 6 1 9
print(my_df.mode()) # Computing the mode of all columns # A B # 0 1 8 |
print(my_df.mode()) # Computing the mode of all columns # A B # 0 1 8