2. Tabular Data Mastery with Pandas
Aggregating with groupby(), Joining with merge() & Pivot Tables
Answer real business questions in Pandas: summarize revenue by segment with groupby().agg(), combine normalized tables using pd.merge(), and reshape summaries with pivot_table().
- Compute multiple named aggregations cleanly with groupby().agg()
- Combine separate DataFrames accurately with left/inner pd.merge() and validate= checks
- Reshape long transaction tables into executive summary grids with pivot_table()
Once your dataset is clean, leadership doesn't want a 50,000-row spreadsheet—they want answers: "Which product category drives the most revenue? How does Pro-tier average order value compare to Free-tier? What happened to Books revenue in November vs October?"
In Pandas, three workhorse methods answer 90% of business analytics questions: groupby(), merge(), and pivot_table().
1. Split-Apply-Combine with groupby().agg()
Every groupby() follows a three-step Split → Apply → Combine mental model:
- Split the table into invisible sub-tables—one per unique
category(or["region", "category"]). - Apply summary functions (
sum,mean,median,count,nunique) independently to each bucket. - Combine the bucket results back into one tidy summary DataFrame.
Always prefer named aggregations with as_index=False so your output columns have predictable, flat names instead of nested multi-level headers:
summary = (
orders
.groupby("category", as_index=False)
.agg(
total_revenue=("amount", "sum"),
avg_order=("amount", "mean"),
median_order=("amount", "median"),
order_count=("order_id", "count"),
unique_buyers=("customer_id", "nunique"),
)
.sort_values("total_revenue", ascending=False)
)If 120 orders have category = NaN, orders.groupby("category") excludes those 120 rows unless you pass dropna=False (or fill missing labels with "Uncategorized" first). Always verify summary["order_count"].sum() == len(orders)!
2. Joining Normalized Tables Safely with pd.merge()
INNER JOIN
Keeps only rows where both courses.id and enrollments.course_id match.
LEFT JOIN
Keeps every row from the left table (`courses`), returning NULL if no enrollment exists.
pd.merge(..., how='inner') drops unmatched rows; how='left' preserves every left-table order so total revenue never silently shrinks.
In real databases, orders only holds customer_id, while customer attributes (tier, country, signup_month) live in a separate customers table. Just like SQL JOINs, pd.merge() stitches them together by key:
Join Type (how=) | Keeps Rows From Left (orders) | Keeps Rows From Right (customers) | When to Use |
|---|---|---|---|
"inner" | Only matching keys | Only matching keys | Both sides must exist (careful: drops unmatched orders!) |
"left" | All rows (NaN if no match) | Only matching keys | Enriching orders with attributes without losing revenue |
"right" | Only matching keys | All rows | Auditing customers with zero orders |
"outer" | All rows | All rows | Reconciling two tables to spot mismatches on either side |
enriched = pd.merge(
orders,
customers,
on="customer_id",
how="left",
validate="many_to_one", # Raises MergeError if customers has duplicate IDs!
)The Join Row-Explosion Pitfall (validate=)
Suppose orders has 1,000 rows totaling $50,000. Unknown to you, customers accidentally has two rows for customer_id=42 (one old address, one new address). When you merge without checking, every order from customer 42 duplicates—quietly inflating your revenue report to $54,000 with zero errors raised!
In analytics, an accidental duplicate key in the lookup table silently doubles or triples your revenue sums! Always pass validate="many_to_one" (or "one_to_one") and assert len(merged) == len(orders) after a left enrichment join.
3. Reshaping Grids with pivot_table()
A groupby(["category", "month"]) gives a tall, narrow table—great for plotting, harder for executives to scan across months. pd.pivot_table() turns long rows into a crisp 2D cross-tabulated matrix:
matrix = pd.pivot_table(
orders,
values="amount",
index="category", # One row per category
columns="month", # One column per month
aggfunc="sum",
fill_value=0, # Replace missing category-month cells with 0 instead of NaN
margins=True, # Adds an "All" row & column for grand totals!
)Notice fill_value=0: if "Office" had zero orders in "2026-10", a pivot table leaves that cell as NaN unless you explicitly tell it fill_value=0.
Try It Yourself in the Playground
Trace a left table join + groupby multi-metric aggregation (orders, revenue, avg_order) + row-count verification in pure Python:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why is how="left" usually safer than the default how="inner" when enriching orders with optional customers details?
Quick Checkpoints
What does adding validate='many_to_one' to pd.merge(orders, customers, on='customer_id', validate='many_to_one') protect against?
Which Pandas method reshapes long rows into a 2D summary matrix with one column per category or month?
You run orders.groupby('region')['amount'].sum(), and the total is $3,000 lower than orders['amount'].sum(). What is the most likely culprit?