← Back to Pandas Course | Chapter 7: Grouping & Aggregation | Lesson 7 of 7

Named aggregation

Named aggregation lets you choose clear names for each result column while aggregating.

In this page:

  1. Named aggregation
Syntax
python
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

python
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
  1. Passing a plain string instead of a tuple
  2. Repeating the same output name
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.