pandas for analysis · core
groupby, merge and transform in pandas
Summaries in pandas need a filter, a safe merge and a named aggregation. A merge can duplicate rows or lose rows, and groupby drops missing keys by default.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Filter first (status and date as a real datetime with a half-open range), then merge, then aggregate.
- Merge with how="left" and validate="many_to_one" (raises MergeError on duplicate keys). Use indicator=True to count unmatched rows and compare row counts before and after.
- Duplicate keys in the right table make orders match twice, so amounts count twice. Orders with no match get NaN, and groupby drops NaN keys by default (dropna=True), so their revenue vanishes from the report.
- Use dropna=False or fill with "Unknown" so every rupee stays in a group. Check that the total of amount is the same before and after the merge.
- Named aggregation: groupby("city").agg(orders=("order_id", "count"), revenue=("amount", "sum")).
- Read keys with the same explicit dtype on both sides. If one id file has a text value, the column loads as text (the str dtype in pandas 3) and merging with int64 raises a ValueError. Do not cast ids to float.
- transform returns values aligned to the original rows; agg returns one row per group. Share of city revenue: df["amount"] / df.groupby("city")["amount"].transform("sum").
- apply with a Python function runs once per group and is slow. In pandas 3 the grouping columns are no longer passed into the function (include_groups=True was removed). Grouping by a categorical column now defaults to observed=True.
- Do not use drop_duplicates() on the merged table to hide a duplicate-key problem. Fix the key in the right table by a clear rule, for example the latest row.
The red pen
Common traps: mistake → fix
Mistake: Merge then groupby, the totals will match
Fix: check totals before and after; duplicates add and NaN keys disappear.
Mistake: apply is vectorised
Fix: it calls Python once per group.
Mistake: Casting ids to float is fine
Fix: it loses leading zeros and precision.
Easy to hard
Questions interviewers ask, easy to hard
- Write pandas code for orders and revenue by city, with a merge from customers.
- The merged table has more rows and less revenue than finance. Why?
- What does validate="many_to_one" do?
- How do you add each order's share of its city's revenue quickly?
- What changed in pandas 3 that can break old groupby code?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.