17 C
London
Friday, July 11, 2025
HomePandas in PythonGeneral Functions in PythonPandas: How to Calculate Mode in a GroupBy Object

Pandas: How to Calculate Mode in a GroupBy Object

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following syntax to calculate the mode in a GroupBy object in pandas:

df.groupby(['group_var'])['value_var'].agg(pd.Series.mode)

The following example shows how to use this syntax in practice.

Example: Calculate Mode in a GroupBy Object

Suppose we have the following pandas DataFrame that shows the points scored by basketball players on various teams:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'],
                   'points': [10, 10, 12, 15, 19, 23, 20, 20, 26]})

#view DataFrame
print(df)

  team  points
0    A      10
1    A      10
2    A      12
3    A      15
4    B      19
5    B      23
6    C      20
7    C      20
8    C      26

We can use the following syntax to calculate the mode points value for each team:

#calculate mode points value for each team
df.groupby(['team'])['points'].agg(pd.Series.mode)

team
A          10
B    [19, 23]
C          20
Name: points, dtype: object

Here’s how to interpret the output:

  • The mode points value for team A is 10.
  • The mode points values for team B are 19 and 23.
  • The mode points value for team C is 20.

If one group happens to have multiple modes then you can use the following syntax to display each mode on a different row:

#calculate mode points value for each team
df.groupby(['team'])['points'].apply(pd.Series.mode)

team   
A     0    10
B     0    19
      1    23
C     0    20
Name: points, dtype: int64

Note: You can find the complete documentation for the GroupBy operation in pandas here.

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

Pandas: How to Calculate Cumulative Sum by Group
Pandas: How to Count Unique Values by Group
Pandas: How to Calculate Correlation By Group

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories