Análise com GroupBy por região e categoria
Agregue a receita total e a contagem de pedidos por região e categoria de produto e identifique os cinco principais SKUs por margem.
Análise com GroupBy por região e categoria é uma aula grátis de Pandas & NumPy Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Pandas & NumPy Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Pandas & NumPy Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Perguntas Frequentes
A aula “Análise com GroupBy por região e categoria” é grátis?
Sim — o texto completo de “Análise com GroupBy por região e categoria” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Pandas & NumPy Academy, atualize para CoddyKit PRO. O curso de Pandas & NumPy Academy inclui 4 aulas no total.
O que vou aprender em “Análise com GroupBy por região e categoria”?
Agregue a receita total e a contagem de pedidos por região e categoria de produto e identifique os cinco principais SKUs por margem. Você pratica Pandas & NumPy Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Pandas & NumPy Academy?
Nenhuma experiência prévia é necessária. Pandas & NumPy Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Análise com GroupBy por região e categoria”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Pandas & NumPy Academy?
Sim. Cada aula de Pandas & NumPy Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Carregando e auditando o conjunto de dados de vendas
- Cálculos de receita e criação de variáveis
- Análise com GroupBy por região e categoria
- Visualização de tendências mensais