agg
agg (short for aggregate) applies one or more functions to each group or column: df.groupby("k")["v"].agg(["mean", "max"]). Named aggregation, .agg(avg=("v", "mean")), gives you flat, chosen column names in one step.
Syntax
grouped.agg(func) | grouped.agg({"col": ["sum", "mean"]}) | grouped.agg(new_name=("col", "func"))| Part | What it is |
|---|---|
func | A function name string, a callable, a list of them, or a dict of column to functions |
new_name=(col, func) | Named aggregation: output column new_name is func applied to col |
Examples
import pandas as pd
df = pd.DataFrame({"dept": ["Sales", "IT", "Sales", "HR", "IT"],
"salary": [50000, 62000, 58000, 45000, 70000],
"years": [3, 5, 2, 8, 6]})
df.groupby("dept")["salary"].agg(["mean", "max", "count"])Result: mean max count dept HR 45000.0 45000 1 IT 66000.0 70000 2 Sales 54000.0 58000 2
df.groupby("dept").agg(avg_salary=("salary", "mean"),
max_years=("years", "max"),
headcount=("salary", "size"))Result: avg_salary max_years headcount dept HR 45000.0 8 1 IT 66000.0 6 2 Sales 54000.0 3 2
Named aggregation: clean single-level column names.
df.groupby("dept").agg({"salary": ["min", "max"], "years": "sum"})Result: salary years min max sum dept HR 45000 45000 8 IT 62000 70000 11 Sales 50000 58000 5
A dict produces a two-level column header.
Common mistakes
- MultiIndex columns after agg with a dict or list are awkward to use: flatten with df.columns = ["_".join(c) for c in df.columns] or use named aggregation.
- SpecificationError: nested renamer is not supported: the old {"col": {"name": "func"}} syntax was removed; use named aggregation.
- Passing "count" when you want the number of rows: use "size"; count skips NaN.
Practice agg
These drills check your answer on live data, free, no account needed.
- Named aggregationsFor each region, return a DataFrame with three columns: `total_revenue` (sum of revenue), `orders` (number of orders) and `avg_units` (mean units). Index by region.
- Several statistics at onceFor each product, return the minimum, maximum and mean revenue per order. The columns should be `min`, `max` and `mean`, in that order.
Questions
What is the difference between agg and apply in groupby?
agg must return one value per group per column and is optimized for that. apply receives the whole group DataFrame and can return anything, which is flexible but slower.
Can I use agg without groupby?
Yes: df.agg(["mean", "std"]) computes those across all rows, and df.agg({"a": "sum", "b": "max"}) picks a function per column.
Related
- groupbyHow groupby works in pandas: group by one or more columns, apply sum, mean, count or size, get a flat table with as_index=False, and iterate over groups.
- transformHow groupby transform works in pandas: broadcast a group sum or mean to each row, share of group total, group-wise normalization, and transform versus agg.
- describeWhat df.describe returns in pandas: count, mean, std, min, quartiles and max for numeric columns, including text columns, custom percentiles and transposing.
- pivot_tableHow to build a pivot table in pandas with pivot_table: index, columns, values, aggfunc, fill_value for empty cells, margins for totals, several aggregations.