agg() functions
agg applies one or several summary functions to your groups in a single call.
In this page:
Syntax
df.groupby("column").agg("function_name")
df.groupby("column").agg({"column1": "sum", "column2": "mean"})
agg() functions
agg accepts a function name, a list of names, or a dict mapping columns to functions. Common choices are sum, mean, min, max, count and std. It works on Series, DataFrames and groupby objects.
Note:
A dict such as {"salary": "mean", "age": "max"} applies different functions per column.
Example: agg() functions
import pandas as pd
df = pd.DataFrame({"dept": ["A", "B", "A", "B"], "salary": [100, 200, 150, 250], "age": [30, 40, 35, 45]})
print(df.groupby("dept").agg({"salary": "mean", "age": "max"}))
print(df["salary"].agg(["min", "max"]))
# Output:
# salary age
# dept
# A 125.0 35
# B 225.0 45
# min 100
# max 250
# Name: salary, dtype: int64
Related Topics
Common Mistakes
- Using the wrong function name string
- Forgetting agg returns a new object
- Applying numeric functions to text columns
Chapter Summary
- agg takes names, lists or dicts
- Works with groupby
- Dicts vary functions per column
- Common: sum, mean, min, max
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: