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:
# Average package per programmedf.groupby("programme")["package"].mean()# Count of students per programmedf.groupby("programme").size()# Group by two keysdf.groupby(["programme", "year"])["package"].mean()
Multiple aggregations at once
Use agg to compute several summaries together, and name the output columns:
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:
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 columnspd.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:
df.pivot_table(index="programme", # rowscolumns="year", # columnsvalues="package", # cell valuesaggfunc="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
- 01groupby splits rows into groups, aggregates each, and combines — pandas' GROUP BY.
- 02agg computes several named summaries at once; reset_index turns group keys back into columns.
- 03merge joins two DataFrames on a key (how = inner/left/right/outer); concat stacks rows.
- 04pivot_table reshapes long data into a grid with an aggregation — like an Excel pivot.
- 05These four chapters cover the full analyst workflow: load → select → clean → summarise.
