Multiple Aggregations & NamedAgg0%

Multiple Aggregations & NamedAgg

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

Multiple Aggregations & NamedAgg

Reading Time: 8 Mins | Level: Beginner to Advanced


1. Beyond Single Aggregations

In business reporting, a manager rarely wants just the sum of sales. They want the Sum, Average, Minimum, Maximum, and Transaction Count all in one table.

Pandas provides the .agg() (or .aggregate()) method to compute multiple metrics simultaneously across different columns.


2. Using .agg() with Multiple Built-in Functions

Python
import pandas as pd
 
df = pd.DataFrame({
'Branch': ['Delhi', 'Delhi', 'Mumbai', 'Mumbai', 'Delhi'],
'Revenue': [120000, 85000, 140000, 190000, 95000],
'Expenses': [45000, 30000, 50000, 70000, 35000]
})
 
# Multiple aggregations on a single column
summary = df.groupby('Branch')['Revenue'].agg(['count', 'sum', 'mean', 'max'])
print(summary)

Output:

Output
count sum mean max
Branch
Delhi 3 300000 100000.000000 120000
Mumbai 2 330000 165000.000000 190000

3. Applying Different Aggregations to Different Columns

Pass a dictionary where keys are column names and values are lists of aggregation functions:

Python
custom_metrics = df.groupby('Branch').agg({
'Revenue': ['sum', 'mean'],
'Expenses': ['sum', 'max']
})
print(custom_metrics)

4. Modern Best Practice: Named Aggregations (NamedAgg)

When using standard .agg(), Pandas generates hierarchical multi-level column headers (e.g. ('Revenue', 'sum')), which are awkward to query.

Named Aggregation allows you to specify clean, custom output column names directly during the aggregation:

Python
# Modern clean syntax (Pandas 0.25+)
clean_report = df.groupby('Branch', as_index=False).agg(
Total_Revenue=pd.NamedAgg(column='Revenue', aggfunc='sum'),
Avg_Revenue=pd.NamedAgg(column='Revenue', aggfunc='mean'),
Max_Expense=pd.NamedAgg(column='Expenses', aggfunc='max'),
Transactions=pd.NamedAgg(column='Revenue', aggfunc='count')
)
print(clean_report)

Output:

Output
Branch Total_Revenue Avg_Revenue Max_Expense Transactions
0 Delhi 300000 100000.0 45000 3
1 Mumbai 330000 165000.0 70000 2

Interactive Quiz

Multiple Choice Questions

Question 1
Which method allows computing multiple statistical aggregations (e.g. sum, mean, max) simultaneously in a GroupBy?
Question 2
What problem does pd.NamedAgg solve in Pandas?
Question 3
How do you apply 'mean' to column 'Age' and 'sum' to column 'Salary' in a single groupby call?
Question 4
Can custom Python functions or lambda expressions be passed into .agg()?
Question 5
What is the difference between agg('count') and agg('size')?

Next Lesson

Pivot Tables & Cross-Tabulations (pivot_table, crosstab)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext