21.9 C
London
Tuesday, July 22, 2025
HomePandas in PythonGeneral Functions in PythonPandas: How to Use Groupby with Multiple Aggregations

Pandas: How to Use Groupby with Multiple Aggregations

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 basic syntax to use a groupby with multiple aggregations in pandas:

df.groupby('team').agg(
    mean_points=('points', np.mean),
    sum_points=('points', np.sum),
    std_points=('points', np.std))

This particular formula groups the rows of the DataFrame by the variable called team and then calculates several summary statistics for the variable called points.

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

Example: Using Groupby with Multiple Aggregations in Pandas

Suppose we have the following pandas DataFrame that contains information about various basketball players:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['Mavs', 'Mavs', 'Mavs', 'Heat', 'Heat', 'Heat'],
                   'points': [18, 22, 19, 14, 14, 11],
                   'assists': [5, 7, 7, 9, 12, 9]})

#view DataFrame
print(df)

   team  points  assists
0  Mavs      18        5
1  Mavs      22        7
2  Mavs      19        7
3  Heat      14        9
4  Heat      14       12
5  Heat      11        9

We can use the following syntax to group the rows of the DataFrame by team and then calculate the mean, sum, and standard deviation of points for each team:

import numpy as np

#group by team and calculate mean, sum, and standard deviation of points
df.groupby('team').agg(
    mean_points=('points', np.mean),
    sum_points=('points', np.sum),
    std_points=('points', np.std))

      mean_points	sum_points	std_points
team			
Heat	13.000000	        39	  1.732051
Mavs	19.666667	        59	  2.081666

The output displays the mean, sum, and standard deviation of the points variable for each team.

You can use similar syntax to perform a groupby and calculate as many aggregations as you’d like.

Additional Resources

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

How to Count Unique Values Using Pandas GroupBy
How to Apply Function to Pandas Groupby
How to Create Bar Plot from Pandas GroupBy

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