DS 208 · Week 7

pandas II: Grouping, Merging & Reshaping

Summarising by category, joining two tables on a shared key, and pivoting data between long and wide: the operations behind most analyses.

Programming for Data Science · University of the Philippines Cebu

Outline

Grouping, merging and reshaping

Definition

What is grouping?

In plain words: grouping sorts the rows into piles by a key column, computes one summary per pile, and stacks the summaries into a small table with one row per pile.

Formally

rg = f( { xi : ki = g } )  for every distinct key value g

PartFor the eight cities
ki, the keythe region of city i: Luzon, Mindanao or Visayas
xi, the valuethe population of city i
Gg, a groupthe rows with ki = g: GLuzon = Quezon City, Manila, Baguio
f, the summarythe mean
rg, one result rowrLuzon = (2,960,000 + 1,847,000 + 366,000) ÷ 3 = 1,724,333
In pandascities.groupby("region")["pop"].mean()

Wickham, H. (2011). The split-apply-combine strategy for data analysis. Journal of Statistical Software 40(1).

key ki value xi city region pop Quezon City Luzon 2.96M Manila Luzon 1.85M Baguio Luzon 0.37M GLuzon 1,724,333 Davao Mindanao 1.78M Cagayan de Oro Mindanao 0.73M GMindanao 1,252,500 Cebu Visayas 0.96M Iloilo Visayas 0.46M Tacloban Visayas 0.25M GVisayas 557,333 group Gg rg = mean 8 rows → 3 result rows, one per distinct key
Key terms

Ten terms introduced this week

group by

Sort the rows into piles, one pile per distinct value of a column.

e.g. df.groupby("region") makes one pile per region

aggregation

A summary that turns many values into one: mean, sum, count, max.

e.g. .agg(["mean", "count"])

split-apply-combine

Split into groups, summarise each group, stack the answers into one small table.

e.g. 34,079 project rows → 18 region rows

key

The column two tables share, used to decide which rows belong together.

e.g. city in both the population and the area table

merge / join

Combine two tables side by side by matching their key values, like Excel's VLOOKUP.

e.g. pd.merge(pops, areas, on="city")

inner / left / outer join

Which rows survive a merge: only matches, every row of the left table, or everything.

e.g. how="left"

concat

Stack tables under (or beside) each other, without matching any key.

e.g. pd.concat([january, february])

long vs wide

Long: one measurement per row. Wide: a grid, with one category spread across the columns.

e.g. city, year, sales vs city, 2024, 2025

pivot / pivot_table

Turn long into wide; pivot_table also summarises repeats, like an Excel PivotTable.

e.g. pivot_table(index="region", columns="year", …)

melt

Turn wide back into long: every cell of the grid becomes its own row.

e.g. wide.melt(id_vars="city")

Previous session

Filtering selects rows but does not summarise per group

Filtering can keep the Visayan cities, but "the average population of each region" requires a summary per category. Grouping provides this.

Terms from week 6

DataFrame
a spreadsheet-like table controlled with code: rows and named columns
Series
one column on its own: values plus their row labels
index
the row labels down the left edge (0, 1, 2… unless set otherwise)
NaN
"not a number": pandas' mark for a missing value

Two tables this week

cities: a tiny table (city, region, pop) small enough to check every row by eye. projects: the 34,079 flood-control projects from week 6 (contract_id, region, year, budget, status). Both are called df in the code; the column names identify which one it is.

One subset at a time

Filtering gives one subset. Grouping gives every subset at once.

Multiple tables

Many questions require two tables joined on a shared column.

About the tool

The groupby pattern is older than pandas

SQL

GROUP BY

Databases have long grouped rows before summarising them.

2011

A name

Hadley Wickham calls it split-apply-combine and builds an R package around it.

pandas

groupby

Its user guide is titled “Group by: split-apply-combine”.

SourceH. Wickham, “The Split-Apply-Combine Strategy for Data Analysis,” J. Statistical Software 40(1), 2011; pandas user guide: Group by

About the tool

The same three steps in three tools

Sourcepandas user guide: Group by; dplyr reference: group_by

Runnable code

Code on these slides runs in the browser

As in weeks 5 and 6, a block with a ▶ Run / Edit button runs in the browser and can be changed and run again. The first run downloads Python and pandas, which takes 10 to 20 seconds.

The browser has an older pandas

Printed outputs on the slides come from the lecture laptop, which runs pandas 3. The browser runs pandas 2.2, so text columns print as object instead of str. Blocks that download the flood data have no button; the notebook runs those.

import io, sys print("pandas version:", pd.__version__) print("64-bit Python:", sys.maxsize > 2**32) t = pd.read_csv(io.StringIO("city,pop\nCebu,964000")) print(t.dtypes) pandas version: 3.0.5 64-bit Python: True city str pop int64 dtype: object
  • pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browser
  • t.dtypeseach column’s type: str on the laptop and object in the browser
Part A

Grouping

Split, apply a summary, combine.

Week 6 computed one summary of a whole column, such as df["pop"].mean(). This part computes the same summary once per category, in one line.

Definition

Definition: group by

Formally

The rows i = 1…n split into groups Gg = { i : ki = g }, one per distinct key g. Every row lands in exactly one group, so the group sizes add up to n. Three kinds of apply follow:

aggregate: one value f(Gg) per group · transform: row i gets f(Gki), so n rows come back · filter: keep all of Gg or none of it, by a test on the group

PartApplied to the eight cities
groupsLuzon 3, Mindanao 2, Visayas 3: 3 + 2 + 3 = 8 rows
aggregate3 rows, one mean per region
transform8 rows; Cebu gets the Visayas mean, 557,333
filter: mean > 1,000,0005 rows; all three Visayas cities go, because 557,333 < 1,000,000

Wickham (2011), as above; McKinney, W. (2022). Python for Data Analysis, 3rd ed., ch. 10.

aggregate .mean() 3 rows: one per group transform .transform("mean") 8 rows: one per input row filter .filter(mean > 1M) 5 rows: whole groups kept Luzon · 1,724,333 Mindanao · 1,252,500 Visayas · 557,333 Quezon City · 1,724,333 Quezon City Manila · 1,724,333 Manila Baguio · 1,724,333 Baguio Cebu · 557,333 Cebu (dropped) Iloilo · 557,333 Iloilo (dropped) Tacloban · 557,333 Tacloban (dropped) Davao · 1,252,500 Davao Cagayan de Oro · 1,252,500 Cagayan de Oro
The pattern

Split, apply, combine

Group the rows by a category, apply a summary to each group, then combine those summaries into a small result table. The same pattern recurs throughout data analysis.

To group by a column means to sort the rows into piles, one pile per distinct value (every "Visayas" row in one pile). An aggregation is a summary that turns many values into one — mean, sum, count, max.

Receipts are sorted into one pile per store (split), each pile is added up (apply), and the totals are written on one sheet (combine).

Split

Rows fall into buckets by region.

Apply

Each bucket gets a summary — mean, sum, count.

Combine

One row per group, stacked into the answer.

The cities table

Eight cities in three regions

Parts A to C use one small table typed on the slide: eight cities, the island group each belongs to, and an approximate 2020 census population. Week 6’s five cities are among them.

  • csv_text = """…"""the table as CSV text: a header line, then one city per line
  • pd.read_csv(io.StringIO(csv_text))read the text as if it were a file, as in week 6
  • regionhere the island group (Luzon, Visayas, Mindanao), not the flood data’s administrative region
import io csv_text = """city,region,pop Quezon City,Luzon,2960000 Manila,Luzon,1847000 Baguio,Luzon,366000 Cebu,Visayas,964000 Iloilo,Visayas,457000 Tacloban,Visayas,251000 Davao,Mindanao,1777000 Cagayan de Oro,Mindanao,728000""" cities = pd.read_csv(io.StringIO(csv_text)) print(cities) city region pop 0 Quezon City Luzon 2960000 1 Manila Luzon 1847000 2 Baguio Luzon 366000 3 Cebu Visayas 964000 4 Iloilo Visayas 457000 5 Tacloban Visayas 251000 6 Davao Mindanao 1777000 7 Cagayan de Oro Mindanao 728000
Conceptual model

Eight cities produce three summary rows

8 rows split by region apply mean combine Quezon City Manila Baguio Cebu Iloilo Tacloban Davao Cagayan de Oro Luzon ×3 → 1,724,333 Mindanao ×2 → 1,252,500 Visayas ×3 → 557,333 region · mean Luzon · 1,724,333 Mindanao · 1,252,500 Visayas · 557,333
Basic groupby

groupby followed by a summary

The code names the column to group on, the column to summarise, and the summary. pandas returns one value per group, indexed by the group name.

A PivotTable with "region" in Rows and "Average of pop" in Values, written as one re-runnable line.

# cities: the table from the start of Part A print(cities.groupby("region")["pop"].mean().round()) region Luzon 1724333.0 Mindanao 1252500.0 Visayas 557333.0 Name: pop, dtype: float64
  • cities.groupby("region")split the cities table into one pile per region
  • ["pop"]in each pile, look only at the population column
  • .mean().round()average each pile’s populations, rounded to whole people
  • Luzon 1724333.0a Series: the region names are its index (row labels); Luzon’s three cities average 1,724,333 people
Exercise · 3 min

.agg() for a per-group report

A list of summaries gives one column for each. .agg() is short for aggregate: “apply these summaries”. It takes one name ("mean") or a list of names in square brackets.

Tasks

  1. Predict which region has the most cities, and which has the largest single city.
  2. Select ▶ Run / Edit and run the code.
  3. Change "max" to "median". For which region are the mean and the median equal, and why?

Result on the lecture laptop (select to reveal)

Luzon and Visayas have 3 cities each, Mindanao 2; Luzon has the largest city (2,960,000: Quezon City). With "median", Mindanao’s mean and median are both 1,252,500: with two cities, the median is the average of the two.

# cities: the table from the start of Part A report = cities.groupby("region")["pop"].agg( ["mean", "max", "count"]) print(report.round())
  • .agg(["mean", "max", "count"])run three summaries on every pile; each one becomes a column
  • .round()round the means to whole people for display
Case study

The flood data, loaded from the course API

The rest of Part A applies the same grouping to real data: the 34,079 flood control projects from weeks 5 and 6, downloaded in one request.

Why not pd.read_csv(url)?

pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.

The browser cannot download the data, so the flood blocks have no Run button; the companion notebook runs them.

import io, requests url = "https://portal.latarak.com/api/flood/export.csv" resp = requests.get(url, timeout=60) df = pd.read_csv(io.StringIO(resp.text)) print(df.shape) (34079, 15)
  • requests.get(url)download the whole table in one request, as in weeks 5 and 6
  • pd.read_csv(io.StringIO(resp.text))read the downloaded text as if it were a file
  • (34079, 15)34,079 projects, 15 columns; from here on df is the flood table
Descriptive statistics per group

Seven statistics per group in one call

Each function name in the list is computed per group. This table is a useful first check after any grouping.

Reading count alongside the rest

A mean over 12 projects is far less reliable than a mean over 5,412, and only the count shows which applies.

stats = df.groupby("region").budget.agg([ "count", "sum", "mean", "median", "std", "min", "max"]) print(stats.shape) # sort by whichever column matters top = stats.sort_values("median", ascending=False) print(top.index[:3].tolist()) (18, 7) ['Central Office', 'Region XIII', 'Region XI']
  • .agg(["count", …, "max"])seven summaries of budget per region; each becomes a column
  • stats.shape(18, 7): 18 regions, 7 statistics
  • top.index[:3]the three regions with the largest median project
Applied to 34,079 rows

Split, apply, combine on the project data

The same three steps apply to a real table. The output has one row per region, because the grain changed — grain means "what one row stands for". Before: one project per row. After: one region per row.

Named aggregations

Named aggregation means writing new_name=(column, summary), which sets the output column names. Without it the result can have a MultiIndex: two-level column labels such as ("budget", "sum") that are awkward to use.

by_region = df.groupby("region").agg( projects=("contract_id", "count"), total=("budget", "sum"), typical=("budget", "median"), ) print(len(df), "projects ->", len(by_region), "regions") 34079 projects -> 18 regions
  • .agg(projects=("contract_id", "count"), …)several summaries at once; each is new name = (column, summary)
  • 34079 projects -> 18 regionsthe grain changed: one row per region now
Total and median compared

Total and median identify different regions

Total spend (billions of pesos) Median project (millions of pesos) Region III 267.7 46.3 NCR 159.2 29.2 Region V 155.6 46.8 Region IV-A 134.4 28.7 Region I 109.3 22.8 Region IV-B 98.5 37.6 Central Office 43.6 144.5 The six largest totals, plus Central Office (180 projects). NCR = National Capital Region.
Two keys

Grouping by more than one column

A list of column names gives one row per combination that exists — not per possible combination.

180, not 198

18 regions × 11 years is 198. Eighteen of those pairs never occurred, and groupby does not create them.

g = (df.groupby(["region", "year"]) .budget.sum().reset_index()) print(len(g)) print(18 * 11) # the full region-year grid 180 198
  • groupby(["region", "year"])one pile per region-and-year pair
  • .budget.sum().reset_index()total budget per pile, with the keys back as ordinary columns
  • 180 vs 19818 regions × 11 years would be 198 pairs; 18 pairs have no projects
Worked example

Keep the group key as a column

By default the group key becomes the index (the row labels), which is inconvenient for merging or plotting. One argument avoids the reset_index() that usually follows.

reset_index() moves the row labels back into an ordinary column and numbers the rows 0, 1, 2… again.

Or reset afterwards

The result is the same. Either form may be used for readability, but the choice matters because .loc behaves differently.

# cities: the table from the start of Part A # default: region becomes the INDEX s = cities.groupby("region")["pop"].sum() print(type(s).__name__, s.index.tolist()) # as_index=False: region stays a COLUMN t = cities.groupby("region", as_index=False)["pop"].sum() print(type(t).__name__, t.columns.tolist()) Series ['Luzon', 'Mindanao', 'Visayas'] DataFrame ['region', 'pop']
  • type(s).__name__the name of the result’s type: a Series or a DataFrame
  • as_index=Falsekeep region as an ordinary column instead of the index
New method

transform

Aggregation without collapsing, so that every row can be compared with its own group.

groupby with a summary gives one row per group. transform computes the same per-group summary but copies it back onto every original row.

Worked example

The same calculation with a different output shape

agg gives one row per group. transform gives one row per original row, filled with that row’s group value.

Basis for comparison

Judging whether a project is large for its region requires the region median next to every project.

  • .median()one value per region: 3 rows
  • .transform("median")the same medians, written onto every city’s row: 8 rows, in the table’s order
# cities: the table from the start of Part A print(cities.groupby("region")["pop"].median()) print(cities.groupby("region")["pop"].transform("median")) region Luzon 1847000.0 Mindanao 1252500.0 Visayas 457000.0 Name: pop, dtype: float64 0 1847000.0 1 1847000.0 2 1847000.0 3 457000.0 4 457000.0 5 457000.0 6 1252500.0 7 1252500.0 Name: pop, dtype: float64

Agg writes one line per class on a report; transform writes the class average next to each student's own mark.

Relative comparison

Each project compared with its own region

Two lines convert an absolute number into a relative one, which is usually the more informative measure.

The first project in the frame

₱279.8M in Region V, where the median is ₱46.8M. That is 5.98× a typical project there , which no single-column summary could show.

df["reg_median"] = (df.groupby("region") .budget.transform("median")) df["vs_region"] = df.budget / df.reg_median first = df.iloc[0] print(f"budget {first.budget:,.0f}") print(f"reg_median {first.reg_median:,.0f}") print(f"vs_region {first.vs_region:.2f}") budget 279,839,557 reg_median 46,771,198 vs_region 5.98
  • df["reg_median"] = …each project gets its own region’s median budget
  • df.budget / df.reg_medianhow many times its region’s typical project this one costs
  • vs_region 5.98the first project costs about six times its region’s median
Correctness check

Exactly 17,036 above and 17,036 below the median

filter

Keep whole groups, not rows

Different from a boolean mask (week 6: a True/False per row that picks rows): here the test runs per group, and either the whole group stays or the whole group goes.

A lambda is a tiny function written in one line, with no name. lambda g: len(g) > 3000 means "given a group g, answer True if it has more than 3,000 rows".

Use: keeping only groups with enough data

Comparing regions with 12 projects against ones with 5,000 is rarely fair; this drops the small groups in one line.

big = df.groupby("region").filter( lambda g: len(g) > 3000) print(big.region.nunique(), len(big)) print(sorted(big.region.unique())) 4 16291 ['National Capital Region', 'Region I', 'Region III', 'Region IV-A']
  • .filter(lambda g: len(g) > 3000)keep every row of a region whose pile has more than 3,000 projects
  • 4 162914 regions pass, with 16,291 projects between them
rank

Position within a group, not overall

Another transform-shaped tool: it returns one value per row, giving each project’s position in its own region.

method="min" for ties

Two projects at the same budget both get the lower rank, which matches the usual meaning of "joint first".

A class ranking per section, where a student is "3rd in the section" rather than "412th in the school".

df["rank_in_region"] = (df.groupby("region") .budget.rank(ascending=False, method="min")) # the biggest project in each region top = df[df.rank_in_region == 1] print(len(top)) biggest = top.nlargest(2, "budget").set_index("region").budget print((biggest / 1e6).round(1)) # millions of pesos 18 region Central Office 1447.5 Region XI 989.1 Name: budget, dtype: float64
  • .rank(ascending=False, method="min")1 = the largest budget within its region
  • df[df.rank_in_region == 1]the largest project of each region: 18 rows
  • / 1e6show the budgets in millions of pesos
Cumulative share

Concentration of spending within one region

Sort descending (biggest first), take a running total, divide by the sum. The result shows how few projects account for half the money.

A running total (cumsum, "cumulative sum") adds each value to everything above it: 5, 3, 2 becomes 5, 8, 10.

Region III: a quarter of projects account for half

Its top 1,357 projects — 25.1% of them — account for 50% of its ₱267.7B. This is concentrated, but not extreme.

r3 = (df[df.region == "Region III"] .sort_values("budget", ascending=False)) r3["cum_share"] = r3.budget.cumsum() / r3.budget.sum() half = (r3.cum_share <= .5).sum() + 1 print(half, "of", len(r3), "projects") print(round(half / len(r3), 3)) 1357 of 5412 projects 0.251
  • r3.budget.cumsum() / r3.budget.sum()running total of the budget, as a share of the region’s whole budget
  • (r3.cum_share <= .5).sum() + 1how many projects, largest first, it takes to reach half
Cumulative share, drawn

A quarter of Region III’s projects hold half of its budget

0% 25% 50% 75% 100% 0 1,000 2,000 3,000 4,000 5,000 5,412 1,357 largest projects = half of the money Region III projects, largest budget first (5,412 in all) equal shares share of the region's budget
Review question

Question (select to reveal the answer)

What does df.groupby("region")["pop"].sum() return?

A · one total for the whole column
B · one total per region
C · the original rows, sorted
D · a count of regions

B — one total per region.

Grouping produces one summary row per distinct group value, indexed by that value. A plain df["pop"].sum() would give the single grand total (A).

Exercise · 8 min

Relative comparison with transform

1 · Group the data

Build by_region with projects, total and median. Confirm it has 18 rows.

2 · Find the disagreement

Which region leads on total? Which leads on median? Explain in one sentence why they differ.

3 · Compute a relative measure

Use transform to add vs_region. Find the project with the highest ratio , the largest project relative to its region.

4 · Check the result

Count how many rows are above vs below their region median. An uneven split indicates a misaligned transform.

Review question

Question (select to reveal the answer)

Which tool compares each project with its own region’s median budget?

A · groupby(...).agg("median") — then merge it back
B · groupby(...).transform("median") — it returns one value per original row
C · groupby(...).filter(...)
D · pivot_table with aggfunc="median"
B. transform returns a result aligned to the original index — 34,079 values for 34,079 rows — so it fits directly into a new column. A works but takes an extra merge and a chance to misalign; C keeps or drops whole groups; D changes the grain entirely.
Part B

Merging

Two tables, one shared key, joined into one.

Part A used one table. This part adds columns from a second table by matching rows on a shared column, the code equivalent of Excel's VLOOKUP.

Definition

Definition: join

Formally

L ⋈ R = { (l, r) : l ∈ L, r ∈ R, key(l) = key(r) }

That is the inner join. A left join also keeps every row of L with no partner, filling R’s columns with NaN; an outer join keeps the unmatched rows of both sides.

Partpops ⋈ areas, on city
keyspops: Cebu, Iloilo, Davao · areas: Cebu, Iloilo, Manila
inner: keys in bothCebu, Iloilo → 2 rows
left: every pops key+ Davao, area NaN → 3 rows
outer: keys in either+ Manila, pop NaN → 4 rows
rows for one keynL(k) × nR(k): Cebu twice in each table gives 2 × 2 = 4 rows

The circles hold key values, not rows, so they cannot show the last line: a repeated key multiplies rows. validate=, later in this part, catches it.

Codd, E. F. (1970). A relational model of data for large shared data banks. Communications of the ACM 13(6).

keys of pops (left) keys of areas (right) Davao Cebu Iloilo Manila how="inner": 2 rows how="left": 3 rows how="outer": 4 rows
Motivation

Related data stored in separate tables

Population sits in one file, land area in another. Both have a city column — the key. Merging aligns them so that density can be computed.

Key terms

key
the column both tables share, used to decide which rows belong together (here city)
merge / join
combine two tables side by side by matching their key values; pandas says merge, databases say join

Excel's VLOOKUP finds each city from sheet 1 in sheet 2 and copies its area across. merge does that for every row and every column at once.

Table 1

city, region, pop

Table 2

city, area_km2

Shared key

city, matched row by row.

Exercise · 4 min

merge on the shared column

on= names the key. pandas matches rows where the key agrees and joins the columns into one wider table, so population and land area sit in the same row.

Tasks

  1. Predict the most densely populated city.
  2. Select ▶ Run / Edit and run the code.
  3. Change ascending=False to ascending=True. Which cities are least dense, and why?

Result on the lecture laptop (select to reveal)

Manila: 43,976 people per km², more than twice Quezon City’s 17,209. With ascending=True the least dense come first: Davao (727 per km²), Tacloban (1,243) and Cagayan de Oro (1,763). Davao covers 2,444 km², so its people are spread thin.

SourceLand areas from each city’s Wikipedia article, rounded to whole km²; populations are approximate 2020 census figures.

# cities: the table from the start of Part A areas = pd.DataFrame({ "city": ["Quezon City", "Manila", "Baguio", "Cebu", "Iloilo", "Tacloban", "Davao", "Cagayan de Oro"], "area_km2": [172, 42, 58, 315, 78, 202, 2444, 413]}) both = pd.merge(cities, areas, on="city") both["density"] = both["pop"] / both["area_km2"] print(both.sort_values("density", ascending=False).head(3).round())
  • pd.merge(cities, areas, on="city")for each city, find the row of areas with the same city and glue its columns on
  • both["density"] = …population and area now sit in the same row, so dividing gives people per km²
Join types

Four join types, set by how=

how=KeepsUse when
"inner" (default)keys in bothonly complete matches are needed
"left"all of the left tableenrich a main table, keep every row
"right"all of the right tablesame idea, other side
"outer"keys in eitherunmatched rows must be visible
Example with four cities

Three join types on the same two tables

pops city pop Cebu 964000 Iloilo 457000 Davao 1777000 areas city area_km2 Cebu 315 Iloilo 78 Manila 42 how="inner" city pop area_km2 Cebu 964000 315 Iloilo 457000 78 2 rows how="left" city pop area_km2 Cebu 964000 315.0 Iloilo 457000 78.0 Davao 1777000 NaN 3 rows how="outer" city pop area_km2 Cebu 964000.0 315.0 Davao 1777000.0 NaN Iloilo 457000.0 78.0 Manila NaN 42.0 4 rows
Worked example

validate= converts a silent error into an exception

The most harmful merge error runs without failing: a duplicated key silently doubles the rows, and every later total is wrong. One argument prevents it.

Stating the expected relationship

many_to_one, one_to_one, one_to_many. If the data disagree, pandas raises an error instead of guessing.

many_to_one means "many project rows may share a region, but the lookup table regions lists each region only once". To raise means to stop with an error message (an exception, week 4).

# cities, areas: the tables from the merge exercise ok = cities.merge(areas, on="city", validate="many_to_one") print(len(cities), "rows ->", len(ok), "rows") dup = pd.concat([areas, areas.head(1)]) # Quezon City twice try: cities.merge(dup, on="city", validate="many_to_one") except pd.errors.MergeError as e: print("MergeError:", str(e).splitlines()[0]) 8 rows -> 8 rows MergeError: Merge keys are not unique in right dataset; not a many-to-one merge
  • validate="many_to_one"state the expected relationship: many cities, one area row each
  • pd.concat([areas, areas.head(1)])a copy of areas with Quezon City listed twice
  • MergeErrorthe merge refuses to run, so the doubled row never reaches a total
Exercise · 3 min

indicator=True labels every row

indicator=True adds a column, _merge, saying where each row found its partner: both, left_only or right_only. Counting it is the quickest check after a merge.

Tasks

  1. Predict how many cities end up left_only.
  2. Select ▶ Run / Edit and run the code.
  3. Change != "Davao" to == "Davao", keeping only Davao’s area. How many are left_only now?

Result on the lecture laptop (select to reveal)

1 city, Davao, is left_only; the other 7 are both. Keeping only Davao’s area reverses it: 7 cities are left_only and only Davao is both.

# cities, areas: the tables from the merge exercise some = areas[areas.city != "Davao"] # Davao's area missing m = cities.merge(some, on="city", how="left", indicator=True) print(m["_merge"].value_counts()) print(m[m["_merge"] == "left_only"]["city"].tolist())
  • areas[areas.city != "Davao"]a copy of areas without Davao, to make one key fail
  • m["_merge"].value_counts()how many rows matched on each side
Worked example

Stacking rows or columns without a warning

pd.concat joins tables without a key. With axis=0 (the default) it stacks rows and expects the same column names. With axis=1 it places tables side by side and matches rows by their index labels, not by position.

The silent NaN

The second result has 6 rows, not 3: the labels 0–2 and 5–7 never match, so every cell from the other table is NaN. No warning is raised.

# cities, areas: the tables from the merge exercise # axis=0 (default): rows stacked print(pd.concat([cities.head(2), cities.tail(1)])) # axis=1: columns side by side, matched on the INDEX left = cities[["city"]].head(3) # labels 0, 1, 2 right = areas[["area_km2"]].tail(3) # labels 5, 6, 7 print(pd.concat([left, right], axis=1)) city region pop 0 Quezon City Luzon 2960000 1 Manila Luzon 1847000 7 Cagayan de Oro Mindanao 728000 city area_km2 0 Quezon City NaN 1 Manila NaN 2 Baguio NaN 5 NaN 202.0 6 NaN 2444.0 7 NaN 413.0
  • pd.concat([cities.head(2), cities.tail(1)])the first two rows, then the last one; each keeps its old label
  • pd.concat([left, right], axis=1)side by side, lined up by label: 0, 1, 2 and 5, 6, 7 share nothing
Review question

Question (select to reveal the answer)

A merge expected to be many-to-one returns 68,158 rows from a 34,079-row left frame. What would have caught this at the moment it happened?

A · how="inner" instead of how="left"
B · validate="many_to_one", which raises MergeError on a duplicated right key
C · Sorting both frames before merging
D · Nothing — it can only be found by inspecting totals afterwards
B. The right frame has a duplicated key, so every left row matched twice. validate= checks the expected relationship and raises immediately; indicator=True then shows which rows matched. Without them, the first symptom is a total that is exactly double, three steps downstream.
Break

  Five minutes

Next: reshaping tables.

Part C

Reshaping

Long for analysis; wide for reading.

Parts A and B summarised and combined tables. This part changes their layout (the same numbers as a long list or as a grid) without changing any value.

Definition

Definition: long and wide form

Formally

A long table holds one row (r, c, v) per measurement. A wide table puts the same values in a grid: W[r, c] = v.

pivot needs each (r, c) pair at most once; pivot_table allows repeats and stores W[r, c] = f( { v : rows with that r and c } ). melt reverses it: every cell W[r, c] becomes the row (r, c, W[r, c]).

PartFor the four sales numbers
r → index=region: Luzon, Visayas
c → columns=year: 2024, 2025
v → values=sales
long ↔ wide4 rows ↔ 2 rows × 2 year columns; W[Luzon, 2025] = 25
melt of the grid2 × 2 = 4 rows again

Wickham, H. (2014). Tidy data. Journal of Statistical Software 59(10). Long form is his “tidy” layout: one variable per column, one observation per row.

long: 4 rows (r, c, v) r region c year v sales Visayas 2024 10 Visayas 2025 14 Luzon 2024 22 Luzon 2025 25 pivot melt wide: W[r, c] (2 × 2) r region c 2024 c 2025 Luzon 22 25 Visayas 10 14 each long row is one cell of the grid: W[Luzon, 2025] = 25
Two layouts

Long form for analysis, wide form for reading

Long form has one measurement per row — ideal for grouping and plotting. Wide form spreads a category across columns — ideal for a human to scan.

A long table is a receipt roll with one line per sale; a wide table is a grid with cities down the side and years across the top.

Long

city, year, sales — one number per row.

Wide

city, 2023, 2024, 2025 — years as columns.

Example with four numbers

pivot converts a list to a grid; melt reverses it

long: sales (4 rows) region year sales Visayas 2024 10 Visayas 2025 14 Luzon 2024 22 Luzon 2025 25 pivot_table melt wide (2 rows × 2 year columns) region 2024 2025 Luzon 22 25 Visayas 10 14
Exercise · 3 min

pivot_table spreads a category out

The values of one column become new column headers: each year gets its own column, and each region its own row.

Tasks

  1. Predict the shape of the result.
  2. Select ▶ Run / Edit and run the code.
  3. Add a fifth row, Luzon in 2025 with sales 5, to the three lists. What does the Luzon 2025 cell show now?

Result on the lecture laptop (select to reveal)

2 rows (Luzon, Visayas) by 2 year columns. With the extra row, Luzon 2025 shows 30: aggfunc="sum" adds the two Luzon 2025 rows, 25 + 5. Plain pivot would raise an error on the repeated pair.

sales = pd.DataFrame({"region": ["Visayas", "Visayas", "Luzon", "Luzon"], "year": [2024, 2025, 2024, 2025], "sales": [10, 14, 22, 25]}) wide = sales.pivot_table( index="region", columns="year", values="sales", aggfunc="sum") print(wide)
  • index="region"one row per region
  • columns="year"one column per year
  • values="sales", aggfunc="sum"fill each cell with the sales, added up if a region-year appears twice
pivot_table

pivot_table aggregates where pivot cannot

pivot fails if a cell would hold more than one value. pivot_table takes an aggfunc (the aggregation to use) and summarises instead.

fill_value for the empty cells

Without it, combinations that never occurred show as NaN — which is accurate but harder to read in a count table.

pt = df.pivot_table(index="region", columns="status", values="budget", aggfunc="count", fill_value=0) print(pt.shape) print(pt.loc[["Central Office", "Region III"], ["Completed", "On-Going"]]) (18, 5) status Completed On-Going region Central Office 121 50 Region III 4424 822
  • aggfunc="count"count the projects in each region-status cell instead of adding budgets
  • fill_value=0write 0, not NaN, where a region has no project of that status
  • (18, 5)18 regions by 5 statuses; two of each are printed
Wide → long

melt folds columns into rows

melt is the reverse of a pivot. It keeps an id column and gathers the rest into a name/value pair, the tidy shape most tools and plots expect.

To melt a table is to turn wide into long: each cell of the grid becomes its own row, labelled with the column heading it came from.

# sales, wide: the tables from the pivot_table exercise long = wide.reset_index().melt( id_vars="region", var_name="year", value_name="sales") print(long) region year sales 0 Luzon 2024 22 1 Visayas 2024 10 2 Luzon 2025 25 3 Visayas 2025 14
  • wide.reset_index()make region an ordinary column again
  • id_vars="region"the column to keep as it is
  • var_name="year", value_name="sales"names for the two new columns: the old headers and the old cells
melt

Wide to long for plotting

Most plotting libraries want long form: one row per observation, with the variable name in a column. melt is the inverse of pivot.

id_vars are the columns to keep

Everything not named there gets folded into the variable/value pair.

wide = df.pivot_table(index="region", columns="year", values="budget", aggfunc="sum") long = wide.reset_index().melt( id_vars="region", var_name="year", value_name="total") print(wide.shape, "->", long.shape) print(long.total.isna().sum(), "empty region-years") (18, 11) -> (198, 3) 18 empty region-years
  • df.pivot_table(…)total budget per region and year: 18 rows × 11 year columns
  • .melt(…)one row per cell: 18 × 11 = 198 rows, including the 18 empty ones
crosstab

A frequency table of two categories

A shortcut for the count-only pivot: given two columns, it counts every combination. crosstab is short for "cross-tabulation" — a table of counts with one category down the side and another across the top.

normalize turns counts into rates

normalize="index" makes each row sum to 1, so regions of very different sizes can be compared fairly.

print(pd.crosstab(df.region, df.status).shape) # as shares within each region shares = pd.crosstab(df.region, df.status, normalize="index") print(shares.loc[["Region III"], ["Completed", "On-Going"]].round(3)) (18, 5) status Completed On-Going region Region III 0.817 0.152
  • pd.crosstab(df.region, df.status)count the projects for every region-status pair: 18 × 5
  • normalize="index"divide each row by its total, so each region’s shares add up to 1
  • 0.81781.7% of Region III’s projects are completed
Choosing a tool

Five tasks and the corresponding tools

TaskUseRows out
One summary per groupgroupby().agg()one per group (18)
Each row vs its groupgroupby().transform()same as input (34,079)
Position within groupgroupby().rank()same as input (34,079)
Keep or drop whole groupsgroupby().filter()a subset of input
Counts of two categoriespd.crosstab()a grid (18×5)
Exercise · 4 min

Most densely populated city per region

One question that needs all three parts: merge two tables, derive a column, then group. Each step is one line.

Tasks

  1. Predict which region has the most densely populated city.
  2. Select ▶ Run / Edit and run the code.
  3. Change .max() to .mean(). Does the order of the regions change?

Result on the lecture laptop (select to reveal)

Luzon (Manila, 43,976 people per km²), then Visayas (Iloilo, 5,859) and Mindanao (Cagayan de Oro, 1,763). With .mean(): Luzon 22,499, Visayas 3,387 and Mindanao 1,245, the same order.

# cities, areas: the tables from the merge exercise both = cities.merge(areas, on="city") both["density"] = both["pop"] / both["area_km2"] print(both.groupby("region")["density"].max().round())
  • cities.merge(areas, on="city")merge (Part B): population and area in one table
  • both["density"] = …a derived column (week 6): people per km²
  • .groupby("region")["density"].max()group (Part A): the highest density in each region
Review question

Question (select to reveal the answer)

A merge must keep every row of the left table, matched or not. Which how=?

A · "inner"
B · "left"
C · "right"
D · "outer"

B — "left".

A left join keeps all left rows, filling unmatched right columns with NaN. "inner" would drop the rows that did not match.

This week's lab

Group, merge, and reshape

The lab summarises a dataset by category, joins it to a second table on a key, and pivots the result between long and wide to answer set questions. ~45 minutes.

Lab tasks

groupby.agg, merge(on=, how=), pivot_table, and melt.

Optional extension

Group by two columns at once: groupby(["region", "year"]).

Summary

Grouping, merging and reshaping: summary

Glossary

Terms introduced this week

Grouping

group by
sort rows into piles, one per distinct value of a column
aggregation
a summary that turns many values into one (mean, sum, count)
split-apply-combine
group, summarise each group, stack the answers into one table
named aggregation
new_name=(column, summary) inside .agg(): sets the output column names
grain
what one row stands for: a project, a region, a region-year
median
the middle value once sorted; "a typical one"
transform
a per-group summary copied back onto every original row
lambda
a tiny one-line function with no name: lambda g: len(g) > 3000
running total (cumsum)
each value plus everything before it: 5, 3, 2 → 5, 8, 10
reset_index()
move row labels back into an ordinary column; rows numbered 0, 1, 2…

Merging & reshaping

key
the shared column used to match rows between two tables
merge / join
combine two tables side by side by matching keys (VLOOKUP)
inner / left / outer join
keep matches only / every left row / every row from both
join type (how=)
the setting that picks inner, left, right or outer
validate= / indicator=
merge safety checks: stop on duplicate keys / label where each row matched
concat
stack tables under or beside each other, no key matching
long vs wide
one measurement per row vs a grid with a category across the columns
pivot / pivot_table
long → wide; pivot_table also summarises repeats (Excel PivotTable)
melt
wide → long: each grid cell becomes a row
crosstab
a table counting every combination of two categories
Preparation for next week

Practice & reading

Next Week

Data visualization with matplotlib & seaborn

Turning a summarised table into a chart that shows the pattern clearly, and the small set of plot types used most often.

DS 208 · Programming for Data Science