Pandas: How to Use Groupby with Multiple Aggregations


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

Leave a Reply

Your email address will not be published. Required fields are marked *