The agg() Method
Apply multiple aggregation functions at once with agg(), pass a dict to compute different stats for different columns.
Why Use agg()?
Calling sum() or mean() directly on a GroupBy object gives you a single statistic. But real analyses often need multiple statistics at once — for example, the total revenue, average order size, and order count per region. The agg() method (short for aggregate) lets you compute all of these in a single, efficient call instead of running separate aggregations and merging results.
Passing a List of Function Names
The simplest use of agg() is to pass a list of function name strings. Pandas applies every function to the selected column and returns a DataFrame where each column corresponds to one function. This approach works with any built-in aggregation name: 'sum', 'mean', 'min', 'max', 'count', 'std', 'median', and others.
import pandas as pd
df = pd.DataFrame({
'region': ['East', 'West', 'East', 'West', 'East', 'West'],
'revenue': [200, 340, 150, 290, 310, 410],
'units': [20, 35, 15, 30, 28, 40]
})
result = df.groupby('region')['revenue'].agg(['sum', 'mean', 'count', 'max'])
print(result)
# sum mean count max
# region
# East 660 220.000000 3 310
# West 1040 346.666667 3 410