Compute the most common or frequently occurring values (modes) across Series or DataFrames using the Pandas mode() method. Handle multimodal distributions, find categorical or numerical modes, and manage missing values.
mode() method calculates the value(s) that appear most frequently in a Series or DataFrame. Unlike mean() or median(), mode() always returns a Series or DataFrame to accommodate datasets with multiple tie values (multimodal distributions).import pandas as pd
s = pd.Series([10, 20, 20, 30, 40], name="SCORES")
print(s)
assert s.shape == (5,)
Expected output
0 10
1 20
2 20
3 30
4 40
Name: SCORES, dtype: int64
mode() on the Series to find its most frequent element.m_val = s.mode()
print(m_val)
assert m_val.iloc[0] == 20
Expected output
0 20
dtype: int64
mode() returns all of them ordered sequentially.multi_s = pd.Series([10, 10, 20, 20, 30], name="VALS")
multi_mode = multi_s.mode()
print(multi_mode)
assert list(multi_mode) == [10, 20]
Expected output
0 10
1 20
dtype: int64
fruits = pd.Series(["apple", "banana", "apple", "cherry", "banana", "apple"], name="FRUIT"), compute its mode using mode() and verify that the first mode equals "apple".mode().fruits = pd.Series(["apple", "banana", "apple", "cherry", "banana", "apple"], name="FRUIT")
answer = fruits.mode()
print(answer)
assert answer.iloc[0] == "apple"
Expected output
0 apple
dtype: object
Practice mode() examples interactively directly in your browser:
Reference: Pandas mode() documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.