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().

5 min readUpdated 2026-11-30
In This Lesson
  • 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:

  1. Split the table into invisible sub-tables—one per unique category (or ["region", "category"]).
  2. Apply summary functions (sum, mean, median, count, nunique) independently to each bucket.
  3. 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:

python
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)
)
GroupBy Silently Drops NaN Keys by Default

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 vs LEFT JOIN in 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 keysOnly matching keysBoth sides must exist (careful: drops unmatched orders!)
"left"All rows (NaN if no match)Only matching keysEnriching orders with attributes without losing revenue
"right"Only matching keysAll rowsAuditing customers with zero orders
"outer"All rowsAll rowsReconciling two tables to spot mismatches on either side
python
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!

Always Check Row Count & validate= on merge()

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:

python
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:

Python 3Try It Live: Left Join + GroupBy Aggregation
Output

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

Check Your Understanding

What does adding validate='many_to_one' to pd.merge(orders, customers, on='customer_id', validate='many_to_one') protect against?

Check Your Understanding

Which Pandas method reshapes long rows into a 2D summary matrix with one column per category or month?

Check Your Understanding

You run orders.groupby('region')['amount'].sum(), and the total is $3,000 lower than orders['amount'].sum(). What is the most likely culprit?