Skip to main content
Albero Academy

GroupBy, Merge & Aggregation

Summarise by category with groupby, combine datasets with merge, and reshape with pivot tables — the analyst's power tools.

Chapter 4Pandas16 min readBeginner friendly
  • #Pandas
  • #GroupBy
  • #Merge

This is where pandas pays off: answering business questions. "Average package per programme", "revenue by month and region", "join students to their programmes". Three tools do it — groupby, merge and pivot_table.

GroupBy — split, apply, combine

groupby splits rows into groups by a column, applies an aggregation to each group, and combines the results into a new table. It's the pandas equivalent of SQL's GROUP BY:

grouping
# Average package per programme
df.groupby("programme")["package"].mean()
# Count of students per programme
df.groupby("programme").size()
# Group by two keys
df.groupby(["programme", "year"])["package"].mean()

Multiple aggregations at once

Use agg to compute several summaries together, and name the output columns:

agg
df.groupby("programme").agg(
students=("name", "count"),
avg_pkg=("package", "mean"),
max_pkg=("package", "max"),
).reset_index()

Merging DataFrames

merge joins two DataFrames on a shared key — exactly like a SQL join. The how argument picks the join type:

joining tables
students = pd.DataFrame({"name": ["Aanya", "Rohan"], "prog_id": [1, 2]})
progs = pd.DataFrame({"prog_id": [1, 2], "prog_name": ["Data", "Full Stack"]})
pd.merge(students, progs, on="prog_id", how="inner")
# how = "inner" | "left" | "right" | "outer"
# Stack rows instead of joining columns
pd.concat([df_jan, df_feb], ignore_index=True)

Pivot tables

A pivot table reshapes long data into a grid — the same idea as Excel pivot tables:

pivot_table
df.pivot_table(
index="programme", # rows
columns="year", # columns
values="package", # cell values
aggfunc="mean", # how to aggregate
)

Practice

Answer three questions on your data with groupby/agg: count and average of a metric per category. Then build a second small DataFrame and merge it in, and finish with a pivot_table summarising a value across two dimensions.

Key takeaways

  1. 01groupby splits rows into groups, aggregates each, and combines — pandas' GROUP BY.
  2. 02agg computes several named summaries at once; reset_index turns group keys back into columns.
  3. 03merge joins two DataFrames on a key (how = inner/left/right/outer); concat stacks rows.
  4. 04pivot_table reshapes long data into a grid with an aggregation — like an Excel pivot.
  5. 05These four chapters cover the full analyst workflow: load → select → clean → summarise.