Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 11/ 160
01. Python & Data Wrangling

GroupBy, Aggregations & Pivot Tables

Aggregate by keys, apply multiple metrics, and reshape summaries with pivot/crosstab.

Intermediategroupby · agg3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Weighted average, done correctly

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.

Key takeaway: agg collapses groups, transform keeps rows; compute ratios from sums, not averages of averages.

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.

Channel mix by region

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.

Key takeaway: pivot_table = groupby + unstack; crosstab for counts and proportions; reconcile totals.

How it works, step by step

Step 1 of 4
Question

1. Define the grain and metrics

State what one output row means (region × month) and which metrics you need.

revenue = sum(amount) · customers = nunique(customer_id)
Key numbers at this step
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
  • pivot on data with duplicate index–column pairs
  • Using apply when agg or transform would do

groupby methods

agg
Best for: Summary tables, one row per group

Strengths: Many metrics at once; readable named output.

Watch out: Loses row-level detail.

transform
Best for: Per-row group features (share, z-score, group fill)

Strengths: Output aligns with the original rows.

Watch out: Requires a function returning one value per group or per row.

pivot_table / crosstab
Best for: Grids and category mixes

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 pivot and 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?
Interview tip: Mention reconciliation: "I check that the grouped totals equal the raw total". It's the habit that catches silent NaN-key and filter errors.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply GroupBy, Aggregations & Pivot Tables with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Data Type Conversion & String Cleaning
Next topic
Merging, Joining & Concatenating Data