Chain .groupby("col") with .agg(...) using named aggregation tuples (new_col=("target_col", "func")) to compute multiple statistics like count and mean with clean, flat column names—or call .groupby("col")["target_col"].agg(["count", "mean"]) when summarizing a single column.
Basic Example
import pandas as pd
df = pd.DataFrame({
"department": ["Sales", "Sales", "Engineering", "Engineering", "Engineering"],
"employee": ["Alice", "Bob", "Charlie", "David", "Eve"],
"salary": [70000, 80000, 110000, 120000, None],
"bonus": [5000, 7000, 10000, 12000, 9000],
})
# 1. Recommended: Named aggregation produces clean, single-level column names
summary = df.groupby("department", as_index=False).agg(
total_rows=("employee", "size"), # Counts all rows (including NaN)
valid_salaries=("salary", "count"), # Counts non-null salary values only
avg_salary=("salary", "mean"),
total_bonus=("bonus", "sum"),
)
print(summary)
# department total_rows valid_salaries avg_salary total_bonus
# 0 Engineering 3 2 115000.0 31000
# 1 Sales 2 2 75000.0 12000
# 2. Single-column shorthand: Aggregate one Series with a list of functions
salary_stats = df.groupby("department")["salary"].agg(["count", "mean", "median", "std"])
Key Details & Edge Cases
"count"vs."size"for missing (NaN) values:"count"excludesNaN/Nonevalues per column (soEngineeringhasvalid_salaries = 2because Eve’s salary isNone)."size"counts all rows in each group regardless ofNaNvalues (total_rows = 3). Note thatdf.groupby("department").size()returns a singleSeriesof row counts per group.
- Missing groups when grouping on
NaNkeys (dropna=False):- By default (
dropna=True), Pandas silently drops groups whose grouping key isNaNorNone. Passdropna=False(df.groupby("department", dropna=False).agg(...)) if you want missing-category rows preserved as their own group.
- By default (
- Keep group keys as regular columns instead of the row index (
as_index=False):- By default (
as_index=True), Pandas sets the grouping column(s) as the DataFrame index. Passas_index=False(or chain.reset_index()) to keep group keys as ordinary columns ready for merging or CSV export.
- By default (
- Flattening MultiIndex columns when aggregating multiple columns without named tuples:
- Running
df.groupby("department")[["salary", "bonus"]].agg(["count", "mean"])creates a 2-levelMultiIndexheader (("salary", "count"),("salary", "mean"), …). Prefer named aggregation (avg_salary=("salary", "mean")) or flatten afterward withres.columns = ["_".join(col).strip("_") for col in res.columns].
- Running
- Broadcasting group stats back to every original row (
transform):- If you want to add a column to the original DataFrame (e.g., each employee’s department average) without collapsing rows, use
.transform("mean")instead of.agg("mean"):df["dept_avg_salary"] = df.groupby("department")["salary"].transform("mean")
- If you want to add a column to the original DataFrame (e.g., each employee’s department average) without collapsing rows, use
- Avoid
numeric_onlyerrors on mixed-type DataFrames: Callingdf.groupby("department").mean()directly on a DataFrame containing string columns ("employee") raisesTypeError: agg function failed [how->mean,dtype->object]in Pandas 2.0+. Always select numeric target columns explicitly or passnumeric_only=True(df.groupby("department").mean(numeric_only=True)).
Comparison of Pandas groupby Aggregation Patterns
| Pattern | Syntax | Output Shape & Headers | Counts NaN Values? |
Best Used When |
|---|---|---|---|---|
Named Aggregation (.agg) |
df.groupby("g").agg(n=("x", "count"), avg=("x", "mean")) |
DataFrame with flat, custom column names | No ("count") / Yes ("size") |
Production pipelines needing multiple metrics across multiple columns cleanly. |
Single-Column .agg([...]) |
df.groupby("g")["x"].agg(["count", "mean"]) |
DataFrame with count and mean columns |
No | Quickly summarizing one target Series with several built-in or custom functions. |
Group Row Counts (.size()) |
df.groupby("g").size().reset_index(name="n") |
2-column DataFrame of group frequencies | Yes (includes NaN cells) |
Counting total records per group regardless of missing values in individual columns. |
Row-Level Broadcast (.transform) |
df.groupby("g")["x"].transform("mean") |
Series aligned to original DataFrame index | No | Computing group-relative features (e.g., x - group_mean or share of group total). |
You must log in or register to comment.
