⚡0 XP🔥0

GroupBy, Pivot Tables and Merging

Lesson 5 of 7 ⏱ 4 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Summarise data with groupby and named aggregations, reshape with pivot_table, crosstab and melt, combine DataFrames with merge (joins) and concat, and calculate shares, growth and rankings.

GroupBy: split - apply - combine#

groupby splits the rows into groups, applies a calculation to each, and combines the results - the pandas version of SQL GROUP BY and Excel pivot tables.

▶ Try it Yourselfsales.csvPython
Ctrl + Enter to run
हिंदी में समझें

groupby का मतलब है: "बाँटो → हिसाब करो → जोड़ो" (split → apply → combine)।

df.groupby("region")["sales"].sum() = data को region के हिसाब से समूहों में बाँटो, हर समूह की sales जोड़ो, और नतीजा एक table में दिखाओ। यह SQL के GROUP BY और Excel की pivot table जैसा ही है।

Named aggregations with agg#

Several statistics at once, with clear names:

▶ Try it Yourselfsales.csvPython
Ctrl + Enter to run

as_index=False and reset_index#

groupby puts the group keys in the index. Use as_index=False or .reset_index() to get a normal table (handy for merging and charts).

transform - group values on every row#

▶ Try it Yourselfsales.csvPython
Ctrl + Enter to run

Ranking within groups#

df["rank_in_category"] = df.groupby("category")["sales"].rank(ascending=False, method="dense")
top3 = df.sort_values("sales", ascending=False).groupby("category").head(3)

Pivot tables#

▶ Try it Yourselfsales.csvPython
Ctrl + Enter to run

aggfunc can be "sum", "mean", "count", "median", or a list like ["sum", "mean"].

crosstab - counts of two categories#

▶ Try it Yourselfsales.csvPython
Ctrl + Enter to run

melt - wide to long (the opposite of pivot)#

wide = pt.reset_index()[["region", 2024, 2025]]
long = wide.melt(id_vars="region", var_name="year", value_name="sales")   # like Power Query Unpivot

Merging (joins)#

pd.merge(left, right, on="key", how="left")      # or left.merge(right, ...)
how= Like Keeps
"inner" (default) INNER JOIN matching keys only
"left" LEFT JOIN / XLOOKUP all rows of left
"right" RIGHT JOIN all rows of right
"outer" FULL OUTER JOIN everything
▶ Try it Yourselfsales.csv, products.csvPython
Ctrl + Enter to run
Tip

validate="many_to_one" makes pandas raise an error if the right table has duplicate keys - preventing the silent row-multiplication problem you learned about in SQL joins. Use indicator=True to see which rows matched (_merge column).

Other options: left_on="prod_name", right_on="product" when key names differ; suffixes=("_sale", "_master") when both tables have same-named columns.

Concatenating (stacking)#

▶ Try it Yourselfsales.csvPython
Ctrl + Enter to run

Combine many monthly files:

import glob
files = glob.glob("data/sales_*.csv")
all_sales = pd.concat((pd.read_csv(f) for f in files), ignore_index=True)

Time-based grouping#

▶ Try it Yourselfsales.csvPython
Ctrl + Enter to run

Summary#

  • groupby(...).agg(name=(col, func)) creates clear summaries; transform returns group values per row.
  • pivot_table = Excel pivots; crosstab = counts/shares of two categories; melt = unpivot.
  • merge(how=...) joins tables (use validate to avoid duplicates); concat stacks rows.
  • resample groups by time periods; pct_change computes growth.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Region summary

From sales.csv, create summary - one row per region with columns orders (count of order_id), sales (sum) and profit (sum), plus margin_pct = profit / sales × 100 rounded to 1 decimal. Sort by sales descending.

Dataset: sales.csv (already loaded - just use the file name)
2

Category by year pivot

Create pivot = a pivot table of total sales with category as rows and the order year as columns (add a year column from order_date first). Round to 0 decimals.

Dataset: sales.csv (already loaded - just use the file name)
3

Target achievement with merge

Calculate 2025 sales by region, merge with targets.csv (columns region, year, annual_target), and create result with columns region, sales, annual_target, achievement_pct (rounded to 1 decimal), sorted by achievement_pct descending.

Dataset: sales.csv, targets.csv (already loaded - just use the file name)

Quick Quiz

Q1.

What does df.groupby('region')['sales'].sum() return?

Q2.

Which is the pandas equivalent of an Excel pivot table?

Q3.

pd.merge(sales, products, on='product', how='left') is like...

Q4.

What does pd.concat([df_2024, df_2025]) do?

Q5.

What does transform('sum') in a groupby return?