Table of Contents
Groupby with multiple aggregations can be used to summarize data in multiple ways by grouping data using one or more columns and then applying multiple aggregation functions to the resulting groups. This can be done by using a list or dictionary of the aggregation functions and column names as the “agg” argument in the groupby function. This allows for a concise way to summarize data across multiple columns and aggregation functions.
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.