Menu

Grouping, Summaries, and Visualisation

Lesson 5: Grouping, Summaries, and Visualisation

What is a grouped analysis?

Grouping follows a split–apply–combine pattern:

  1. Split records into groups (e.g., by region)
  2. Apply a calculation to each group (e.g., sum of revenue)
  3. Combine the results into a summary table

Use it to compare sales by region, average delivery time by courier, or sign-ups by marketing channel.

Example

summary = (df.groupby('region', as_index=False)
.agg(total_revenue=('revenue', 'sum'),
order_count=('order_id', 'nunique'),
avg_order_value=('revenue', 'mean'))
.sort_values('total_revenue', ascending=False))
print(summary)

How it works

Part

Role

groupby('region')Defines the groups
as_index=FalseKeeps region as a normal column
.agg(name=('column', 'function'))Named aggregations: clear output column names
'nunique'Counts unique orders, avoiding double-counting line items
.sort_values()Orders the result

Common aggregation functions: 'sum', 'mean', 'median', 'count', 'nunique', 'min', 'max', 'std'

Other useful summaries:

Task

Code

Group by two columnsdf.groupby(['region', 'month'])
Pivot-style tablepd.pivot_table(df, values='revenue', index='region', columns='month', aggfunc='sum')
Share of totalsummary['share'] = summary['total_revenue'] / summary['total_revenue'].sum()
Monthly totalsdf.groupby(df['order_date'].dt.to_period('M'))['revenue'].sum()

Create a chart

import matplotlib.pyplot as plt
plt.figure(figsize=(8, 4))
plt.bar(summary['region'], summary['total_revenue'])
plt.title('Total revenue by region')
plt.xlabel('Region')
plt.ylabel('Revenue (₹)')
plt.tight_layout()
plt.show()

Question

Chart

Matplotlib / seaborn

Compare categoriesBar chartplt.bar() / sns.barplot()
Change over timeLine chartplt.plot() / sns.lineplot()
DistributionHistogramplt.hist() / sns.histplot()
RelationshipScatter plotplt.scatter() / sns.scatterplot()
Spread by groupBox plotsns.boxplot()

Always label axes, show units, and use a chart type that makes the comparison easy.

Keeping notebooks reproducible:

  • Put all imports in the first cell.
  • Run Restart & Run All before sharing, to confirm the notebook works top to bottom.
  • Use relative file paths and record library versions (pd.__version__).
  • Avoid editing data by hand outside the code.

Common mistakes

  • Wrong unit of analysis: a line-item table and an order-level table give different counts. Use nunique on order IDs.
  • count vs nunique: count counts non-null rows; nunique counts distinct values.
  • Unlabelled charts: no title, units, or axis labels.
  • Grouping on dirty categories: clean labels before grouping, or "South" and "south " become separate groups.

Try it: Group a sales dataset by region, calculate total revenue, and create a bar chart of the results.


Data Analytics Tutorial



Learn via Video Course

Data Analysis and Processing with Python using Pandas - Data Science Course Logo

Data Analysis and Processing with Python using Pandas - Data Science Course

5 hrs



Get in Touch For Details