0Pricing
Pandas & NumPy Academy · レッスン

地域とカテゴリ別のGroupBy分析

地域と商品カテゴリごとに売上合計と注文数を集計し、利益率に基づく上位5つのSKUを特定します。

「地域とカテゴリ別のGroupBy分析」はCoddyKit上の無料Pandas & NumPy Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはPandas & NumPy Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Pandas & NumPy Academyコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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.

よくある質問

「地域とカテゴリ別のGroupBy分析」レッスンは無料ですか?

はい。「地域とカテゴリ別のGroupBy分析」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Pandas & NumPy Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Pandas & NumPy Academyコースには全4レッスンが含まれています。

「地域とカテゴリ別のGroupBy分析」で何を学びますか?

地域と商品カテゴリごとに売上合計と注文数を集計し、利益率に基づく上位5つのSKUを特定します。 ブラウザで直接実行するハンズオンコードでPandas & NumPy Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Pandas & NumPy Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのPandas & NumPy Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「地域とカテゴリ別のGroupBy分析」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このPandas & NumPy Academyレッスンでコードを書いて実行できますか?

はい。すべてのPandas & NumPy Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 売上データセットの読み込みと監査
  2. 売上計算と特徴量エンジニアリング
  3. 地域とカテゴリ別のGroupBy分析
  4. 月次トレンドの可視化
← Pandas & NumPy Academyに戻る