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]
import statistics                                 # Load statistics
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
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

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top