0Pricing
Pandas & NumPy Academy · Lesson

GroupBy Analysis by Region and Category

Aggregate total revenue and order count by region and product category, and identify the top-5 SKUs by margin.

GroupBy Analysis by Region and Category is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Setting Up GroupBy Analysis

After computing a revenue column, the natural next step is to aggregate it by business dimensions like region and category. The Pandas groupby() call splits the DataFrame into groups, you apply an aggregation function, and Pandas combines the results into a summary table. This split-apply-combine pattern replaces nested SQL GROUP BY queries.

import pandas as pd

df = pd.read_parquet('sales_features.parquet')

# Total revenue by region
region_rev = df.groupby('region')['revenue'].sum().sort_values(ascending=False)
print(region_rev)

Grouping by Category

Aggregate revenue by product category to identify which categories drive the most sales. Use .agg() to compute multiple statistics at once — total revenue, order count, and average order value — in a single pass over the data rather than three separate groupby calls.

cat_summary = df.groupby('category')['revenue'].agg(
    total_revenue='sum',
    order_count='count',
    avg_order_value='mean'
).sort_values('total_revenue', ascending=False)

print(cat_summary)

Grouping by Two Keys: Region and Category

Pass a list of columns to groupby() to create a two-level summary. The result has a MultiIndex — outer level is region, inner is category. Use .reset_index() to flatten it into a plain DataFrame suitable for further filtering or export to a report.

region_cat = df.groupby(['region', 'category'])['revenue'].sum().reset_index()
region_cat.columns = ['region', 'category', 'total_revenue']
region_cat = region_cat.sort_values(['region', 'total_revenue'], ascending=[True, False])
print(region_cat.head(10))

Computing Revenue Share Percentage

Absolute revenue numbers are useful, but revenue share shows each category's contribution to the total. Divide the per-category total by the grand total and multiply by 100. The transform('sum') trick broadcasts the grand total back to each row so you can compute the percentage in a single vectorised step.

df['total_revenue_all'] = df['revenue'].sum()
cat_share = df.groupby('category')['revenue'].sum() / df['revenue'].sum() * 100
cat_share = cat_share.sort_values(ascending=False).round(2)
print(cat_share.rename('revenue_share_%'))

Finding Top-5 SKUs by Revenue

Identify the top-5 products by total revenue using groupby('product')['revenue'].sum().nlargest(5). The nlargest() method is more concise than sorting and slicing. Knowing the top SKUs guides inventory decisions and helps focus promotional efforts where revenue impact is highest.

top5_sku = df.groupby('product')['revenue'].sum().nlargest(5)
print('Top 5 Products by Revenue:')
print(top5_sku)

Order Count vs. Revenue by Region

A region might have high order count but low average order value, or vice versa. Compute both metrics side by side to distinguish volume-driven regions from value-driven ones. Use agg() with a dict to assign descriptive column names and keep the output readable.

region_profile = df.groupby('region').agg(
    order_count=('order_id', 'count'),
    total_revenue=('revenue', 'sum'),
    avg_order=('revenue', 'mean')
).round(2)

print(region_profile.sort_values('total_revenue', ascending=False))

Percentage of Revenue per Region

Compute the share of total revenue contributed by each region. Use groupby().sum() and then divide by the scalar total. This makes it easy to answer executive-level questions like "What percentage of our revenue comes from the North region?" in a single DataFrame expression.

region_rev = df.groupby('region')['revenue'].sum()
region_share = (region_rev / region_rev.sum() * 100).round(2)
region_share.name = 'revenue_share_%'
print(region_share.sort_values(ascending=False))

Filtering Groups by Revenue Threshold

Use groupby().filter() to keep only rows belonging to categories whose total revenue exceeds a threshold. This is useful when you want to remove niche categories from a visualisation or model to focus on material segments. The filter receives a group DataFrame and returns a boolean.

THRESHOLD = 10000

df_major = df.groupby('category').filter(
    lambda g: g['revenue'].sum() >= THRESHOLD
)

print('Major categories:', df_major['category'].nunique())

Month-over-Month Revenue by Category

Combine two groupby keys — month and category — to track how each category's revenue evolves over time. Pivot the result with unstack('category') to get a matrix where rows are months and columns are categories, making it easy to spot seasonal patterns per category.

monthly_cat = df.groupby(['month', 'category'])['revenue'].sum().unstack('category').fillna(0)
print(monthly_cat.round(0))

Top SKU per Region

Identify the single best-selling product in each region by chaining groupby with idxmax(). Group by region and product to get total revenue per combination, then for each region pick the product index with the maximum revenue. This pattern reveals whether different regions prefer different products.

rev_by_region_sku = df.groupby(['region', 'product'])['revenue'].sum()
top_sku_per_region = rev_by_region_sku.groupby('region').idxmax()
print(top_sku_per_region)

Exporting the Summary Table

After computing the region-category summary, export it to Excel with to_excel() so stakeholders who prefer spreadsheets can consume it. Use ExcelWriter to write multiple summary DataFrames to separate sheets in a single workbook. Add a timestamp to the file name so each run produces a versioned output.

from datetime import date

filename = f'sales_summary_{date.today()}.xlsx'

with pd.ExcelWriter(filename, engine='openpyxl') as writer:
    region_profile.to_excel(writer, sheet_name='By Region')
    cat_summary.to_excel(writer, sheet_name='By Category')

print('Saved:', filename)

Quick Check

Test your understanding of Data Analysis concepts from this lesson.

Lesson Recap

In this lesson you learned: grouping by one and two keys to compute revenue summaries, computing revenue share percentages and top-N SKUs, and exporting multi-sheet Excel summary reports. Next up we explore monthly trend visualisation with line charts and moving averages.

Frequently asked questions

Is the “GroupBy Analysis by Region and Category” lesson free?

Yes — the full text of “GroupBy Analysis by Region and Category” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “GroupBy Analysis by Region and Category”?

Aggregate total revenue and order count by region and product category, and identify the top-5 SKUs by margin. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “GroupBy Analysis by Region and Category” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Loading and Auditing the Sales Dataset
  2. Revenue Calculations and Feature Engineering
  3. GroupBy Analysis by Region and Category
  4. Monthly Trend Visualisation
← Back to Pandas & NumPy Academy