Named aggregation
Named aggregation lets you choose clear names for each result column while aggregating.
In this page:
Syntax
df.groupby("column").agg(
new_name=("value_column", "function_name"),
other_name=("other_column", "function_name")
)
Named aggregation
Pass keyword arguments to agg where each value is a pair of (column, function), or use pd.NamedAgg. The keyword becomes the output column name. This gives flat, readable column names and avoids the multi-level header problem.
Note:
Named aggregation requires pandas 0.25 or later.
Example: Named aggregation
import pandas as pd
df = pd.DataFrame({"dept": ["A", "A", "B"], "salary": [100, 300, 200], "age": [30, 40, 50]})
out = df.groupby("dept").agg(
avg_salary=("salary", "mean"),
max_age=("age", "max"),
headcount=("salary", "count"),
)
print(out)
# Output:
# avg_salary max_age headcount
# dept
# A 200.0 40 2
# B 200.0 50 1
Related Topics
Common Mistakes
- Passing a plain string instead of a tuple
- Repeating the same output name
- Forgetting to reset the index if you need the key as a column
Chapter Summary
- kwargs map new name to (column, func)
- Output columns are flat
- NamedAgg is the explicit form
- Requires pandas 0.25 or later
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: