Анализ GroupBy по регионам и категориям
Агрегируйте общую выручку и число заказов по региону и категории товара и находите 5 лучших SKU по марже.
«Анализ GroupBy по регионам и категориям» — бесплатный урок Pandas & NumPy Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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/7) и разблокировать остальной курс Pandas & NumPy Academy, подпишись на CoddyKit PRO. Курс Pandas & NumPy Academy содержит 4 уроков всего.
Чему я научусь в уроке «Анализ GroupBy по регионам и категориям»?
Агрегируйте общую выручку и число заказов по региону и категории товара и находите 5 лучших SKU по марже. Ты практикуешь Pandas & NumPy Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Pandas & NumPy Academy?
Предыдущий опыт не требуется. Pandas & NumPy Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Анализ GroupBy по регионам и категориям»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Pandas & NumPy Academy?
Да. Каждый урок Pandas & NumPy Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Загрузка и проверка набора данных о продажах
- Расчёт выручки и построение признаков
- Анализ GroupBy по регионам и категориям
- Визуализация месячной динамики