πŸ“Š
Your role
Joseph, Mombasa β€” Marketing Ops

Every Monday morning, you paste 4 pivot tables into a dashboard email. Orders from an East African e-commerce marketplace come in all night. Your CFO asks: which product categories drive the most revenue? Which cities are our best performers? How many orders per category per city?

Right now you're doing this by hand. Groupby turns that 45-minute Monday ritual into 7 keystrokes that work whether your data grows to 1M rows or 10M.

200
Orders/week
5
Product categories
5
Cities (IN + KE)

1. Why Groupby? β€” The Punchline First

Before we show you code, here's what one groupby call produces. This is a bar chart of total revenue by product category across your entire marketplace:

Total revenue by product category (KSh)
Bar chart showing total revenue by product category: Home leads at β‚Ή348.7K, followed by Electronics, Fashion, Beauty, and Grocery
What this shows: Every product category contributes different revenue. Home leads at β‚Ή348.7K, followed by Electronics at β‚Ή338.2K. This one chart answers a business question in seconds. That chart came from one groupby call.

The insight: "Every report a business asks for is a groupby in disguise." Your CFO doesn't ask for raw data β€” they ask for summaries. Revenue by category. Orders by city. Average delivery time by region. Groupby is the Python way to answer those questions, whether you're reporting on orders in Jakarta, Johannesburg, or Jaipur. Same 7 keystrokes.

2. Split-Apply-Combine Mental Model

Groupby has three invisible steps. Once you see them, you'll spot groupbys everywhere. Here's the mental model:

SPLIT Group rows by category (5 piles) APPLY Run operation on each pile: .sum(), .mean() COMBINE Stack results into a new Series or DataFrame

When you write df.groupby('category')['amount'].sum(), Python is doing all three steps for you. It splits the 200 orders into 5 piles (one per category), applies sum to each pile's amount column, then combines the 5 sums into a single Series with category names as the index.

πŸ“₯
ecommerce_orders.csv
200 orders from East African marketplace β€’ 9 columns β€’ 15 KB

3. Single-Column GroupBy β€” Revenue by Category

Let's start simple. You want total revenue by category. That's one groupby:

Revenue per category (single groupby)
Category Revenue (KSh)
Beauty 279,480
Electronics 379,560
Fashion 319,840
Grocery 289,720
Home 310,160
Python
What this does: Groups all 200 rows by category, then sums the amount column within each group. Returns a Series where the index is category names and values are totals.

Variations: Other aggregations

You can replace .sum() with any aggregation function:

Mean order amount by category
Count of orders per category
Maximum order size per category

Common aggregations: .sum(), .mean(), .count(), .max(), .min(), .std(), .median().

4. Multiple Aggregations at Once β€” .agg()

Single .sum() is powerful, but your CFO doesn't ask for just one metric. They want: total revenue AND order count AND average order size, all by category. That's a job for .agg():

Revenue, order count, and average basket by category
Category Revenue (KSh) Orders Avg Order
Beauty 279,480 45 6,211
Electronics 379,560 38 9,989
Fashion 319,840 31 10,317
Grocery 289,720 42 6,898
Home 310,160 44 7,049
TOTAL 1,578,760 200 7,894
Python
What this does: In one call, computes three metrics on three different columns. The named parameters (revenue, orders, avg_basket) become column names. This replaces three separate Excel pivot tables with one Python line.

Pro tip: The syntax is column_name=('source_column', 'aggregation_function'). You can chain as many as you need. This is the workhorse of business reporting.

5. Multi-Level GroupBy β€” Revenue by City and Category

Now the business question gets harder: "Which cityΓ—category combinations drive the most revenue?" You can group by two columns at once:

Revenue by city and category (heatmap-style view)
City Electronics Fashion Grocery Home Beauty
Bangalore 78,240 62,180 55,980 63,200 54,460
Mumbai 71,520 64,940 58,840 62,100 58,120
Chennai 69,200 61,840 57,400 62,860 56,680
Nairobi 75,640 63,280 58,960 61,000 54,620
Mombasa 84,960 67,600 58,540 61,000 55,600
Python (long format)
What this does: Returns a Series indexed by city and category pairs. Mombasa+Electronics is highest (84.96K). You can also add .unstack() to pivot it into a wide table (shown above) where cities are rows and categories are columns.
Python (wide format with .unstack())

Insight: Mombasa is your strongest market overall, with especially high Electronics revenue. This two-level groupby reveals regional patterns that single-column groupby missed.

6. Transform vs Agg vs Apply β€” Three Verbs, Three Jobs

GroupBy has three main operations. Knowing which to use saves you from hours of debugging:

Problem: Add a "% of category revenue" column

You want to keep all 200 rows, but add a new column showing what percentage of its category's revenue each order represents. This is a job for transform:

Original data with % of category column (first 5 rows)
order_id amount category pct_of_cat
ORD-01001 8,123 Electronics 2.14%
ORD-01002 5,420 Fashion 1.69%
ORD-01003 3,840 Grocery 1.33%
ORD-01004 9,210 Home 2.97%
ORD-01005 4,150 Beauty 1.48%
Python (.transform adds a column to each row)
What this does: transform broadcasts the category total back to each row. Returns a value for every input row. Good for adding computed columns.

Why three operations?

GroupBy gives you three tools depending on your output shape:

AGG

Shrink rows β€” group of 40 β†’ 1 output row

Use for: summaries, reports, dashboards

TRANSFORM

Same row count β€” 40 rows β†’ 40 rows with group result

Use for: new columns, normalization, z-scores

APPLY

Flexible β€” call custom function on each group

Use for: anything agg/transform can't do

?
1 / 3 questions
What's the difference between .agg() and .transform()?
.agg() shrinks rows (40 β†’ 1 output), .transform() keeps same row count (40 β†’ 40 output with group result)
.agg() is for sums, .transform() is for means
They do the same thing; agg() is older
.transform() only works with numeric columns
What does .groupby(...).size() return?
Total number of rows in the DataFrame
Count of rows in each group (same as .count() on any column)
Memory size in bytes of each group
Number of unique values in the grouping column
Why use observed=True when grouping on a categorical column?
It makes groupby run faster
It only groups by categories actually present in the data (not unused category levels)
It converts strings to numeric codes
It's required for multi-level groupby
Africa & India's Best AI Academy
πŸ€– AI-first πŸŽ“ Placement Assistance

Master Pivot Tables & Cross-Tabulation

Join the Best AI Program: The AI-Era Analyst β€” 5 months, fully online, with placement assistance. Week 1 is free.

Explore The AI-Era Analyst β†’