Multiple aggregations
Pass a list of functions to get several summary numbers per group at once.
In this page:
Syntax
df.groupby("column")["value_column"].agg(["sum", "mean", "count"])
Multiple aggregations
groupby(...)[col].agg(["sum", "mean", "count"]) returns a column per function. On several columns it produces hierarchical column names. You can also pass your own functions alongside built-in names.
Note:
Flatten multi-level columns with df.columns = ["_".join(c) for c in df.columns].
Example: Multiple aggregations
import pandas as pd
df = pd.DataFrame({"dept": ["A", "B", "A", "B"], "salary": [100, 200, 150, 250]})
print(df.groupby("dept")["salary"].agg(["sum", "mean", "count"]))
print(df.groupby("dept")["salary"].agg(["min", lambda s: s.max() - s.min()]))
# Output:
# sum mean count
# dept
# A 250 125.0 2
# B 450 225.0 2
# min <lambda_0>
# dept
# A 100 50
# B 200 50
Related Topics
Common Mistakes
- Confusing multi-level columns
- Passing functions that fail on text
- Forgetting the group key is the index
Chapter Summary
- A list of functions gives multiple columns
- Multiple value columns create hierarchical headers
- Custom functions are allowed
- Flatten headers when needed
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: