GroupBy, Aggregations & Pivot Tables
Aggregate by keys, apply multiple metrics, and reshape summaries with pivot/crosstab.
In plain words
Put rows into groups, calculate something for each group, and collect the answers into a small table.
Think of it like…
Sorting a stack of receipts into piles by shop, adding up each pile on a calculator, then writing the totals on a summary sheet. A pivot table is the same summary written as a grid with shops down the side and months across the top.
Where you’ve seen it
A marketing analyst reports revenue and distinct customers by region and month: df.groupby(["region", "month"]).agg(revenue=("amount", "sum"), customers=("customer_id", "nunique")).reset_index(). For each order's share of its region's revenue she uses df["amount"] / df.groupby("region")["amount"].transform("sum"), which keeps every original row, unlike agg, which returns one row per group.
Words you’ll hear
- Split–apply–combine
- Divide rows into groups, compute per group, assemble the results.
- Named aggregation
agg(new_name=("column", "func"))for readable, flat output columns.- transform
- Returns a Series the same length as the input, aligned to the original rows.
- pivot_table
- Aggregates and reshapes so one key's values become columns.
Visual diagram
Theory & deep dive
groupby, agg and transform
df.groupby("region")["amount"].sum() returns a Series indexed by region; passing a list of keys gives a MultiIndex, and reset_index() flattens it into ordinary columns. agg with named aggregation produces several metrics at once and accepts built-ins ("sum", "mean", "nunique", "median") or your own function. Group on columns, on pd.Grouper(key="date", freq="MS") for monthly buckets, or on a computed Series.
Use transform when you need group-level values on every row: df["share"] = df.amount / df.groupby("region").amount.transform("sum"), df["z"] = (df.amount - g.mean()) / g.std(), or filling missing values with the group median. filter keeps or drops whole groups (g.filter(lambda x: len(x) >= 30)), apply runs arbitrary code per group (flexible but slower), and rank, cumsum and shift inside a group build per-group features. Rows with NaN in the grouping key are dropped unless you pass dropna=False.
Average price per unit by category is g.apply(lambda x: (x.price * x.qty).sum() / x.qty.sum()), not g.price.mean(), which gives every order equal weight. Averaging per-region averages is wrong whenever regions have different sizes.
Pivot tables and crosstabs
pd.pivot_table(df, index="region", columns="month", values="amount", aggfunc="sum", fill_value=0, margins=True) builds a region × month grid with totals. It is groupby plus unstack; use pivot (no aggregation) only when each index–column pair is unique, otherwise it raises an error about duplicates. pd.crosstab(df.region, df.channel, normalize="index") counts or, with normalize, gives row percentages, which is the quickest way to compare category mixes.
Reshape back with melt (wide to long) when you need tidy data for plotting or modelling, and flatten MultiIndex columns with df.columns = ["_".join(map(str, c)).strip("_") for c in df.columns]. Check your result against a simple df.amount.sum(): grand totals should reconcile, and a mismatch usually means dropped NaN keys or a filter you forgot about. For large data, observed=True on categorical keys avoids producing every empty combination.
pd.crosstab(df.region, df.channel, normalize="index").round(2) shows each region's share of orders by channel, so you can see at once that West leans on marketplace sales while South relies on direct.
How it works, step by step
Step 1 of 41. Define the grain and metrics
State what one output row means (region × month) and which metrics you need.
- Grain
- written down
When to use it & trade-offs
What it is
groupby follows split–apply–combine: split rows into groups by one or more keys, apply a function to each group, and combine the results. Named aggregation (df.groupby("region").agg(revenue=("amount", "sum"), orders=("order_id", "nunique"))) gives clean multi-metric summaries. transform returns a result aligned to the original rows (for per-group z-scores or shares), and pivot_table / pd.crosstab reshape summaries into a grid with one dimension across the columns.
Why it matters: Nearly every business question is a grouped summary: revenue by region and month, conversion by campaign, average basket by segment. Pandas groupby is the analyst's equivalent of SQL's GROUP BY, and mistakes such as averaging averages, silently dropping NaN keys or confusing agg with transform produce wrong numbers that look plausible. It's among the most-tested pandas topics.
When to reach for it
- Revenue and counts by segment and period
- Per-group normalisation and ranking features
- Category mix comparisons
When to avoid or be careful
- Averaging group averages
pivoton data with duplicate index–column pairs- Using
applywhenaggortransformwould do
groupby methods
Strengths: Many metrics at once; readable named output.
Watch out: Loses row-level detail.
Strengths: Output aligns with the original rows.
Watch out: Requires a function returning one value per group or per row.
Strengths: Compact, report-ready layouts.
Watch out: Wide results; duplicates and NaN keys need attention.
Interview signals & numbers to know
When this topic comes up
- “Revenue by region and month”
- “Each customer's share of their segment”
- “agg vs transform”
- Pivot tables
- Reconciling totals
Benchmarks & rules of thumb
- dropna=True
- default: NaN keys are dropped
- margins=True
- adds totals to pivot_table
- freq="MS"
- month-start buckets with pd.Grouper
Common mistakes & follow-ups
Common interview mistakes
- Reporting an average of regional averages as the company average.
- Missing that rows with NaN region disappeared from the grouped total.
- Calling
pivotand hitting "Index contains duplicate entries".
Likely interviewer follow-ups
- What's the difference between agg and transform?
- How would you compute a weighted average per group?
- How do you check a grouped result is complete?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply GroupBy, Aggregations & Pivot Tables with data science interview Q&A and hands-on practice.