Chapter 4 introduced merge; real projects push it hard — joining on indexes, chaining several tables, and guarding against the classic bug where a join multiplies your rows. This chapter makes joins reliable.
The join types
how controls which rows survive when keys don't match on both sides:
| how | Keeps |
|---|---|
| inner | Only keys present in both (default) |
| left | All left rows; NaN where no right match |
| right | All right rows; NaN where no left match |
| outer | All keys from both sides |
| cross | Every combination (Cartesian product) |
pd.merge(students, progs, on="prog_id", how="left")# Students with an unknown prog_id are kept, with NaN programme columns.
Keys, indexes & suffixes
# Different key names on each sidepd.merge(a, b, left_on="student_id", right_on="id")# Join on the index instead of a columna.join(b, how="left") # aligns on the indexpd.merge(a, b, left_index=True, right_index=True)# Overlapping non-key columns get suffixespd.merge(a, b, on="id", suffixes=("_2025", "_2026"))
Validate & indicator
pd.merge(orders, customers, on="cust_id",how="left", validate="many_to_one") # each order → one customer# indicator adds a _merge column: left_only / right_only / bothpd.merge(a, b, on="id", how="outer", indicator=True)# Filter _merge == "left_only" to find rows with no match.
Concatenating
concat stacks DataFrames — rows (same columns) or columns (same index):
pd.concat([jan, feb, mar], ignore_index=True) # stack rowspd.concat([q1, q2], keys=["Q1", "Q2"]) # labelled groupspd.concat([features, labels], axis=1) # join columns by index
Practice
Merge an orders table to a customers table with how="left" and validate="many_to_one"; deliberately break the uniqueness and watch it raise. Use indicator=True on an outer join to find unmatched rows. Concatenate three monthly frames into one.
Key takeaways
- 01how = inner/left/right/outer/cross decides which rows survive an unmatched key.
- 02Merge on differently-named columns (left_on/right_on) or on the index (join / left_index).
- 03suffixes disambiguates overlapping non-key column names.
- 04validate= catches unintended many-to-many joins that silently multiply rows.
- 05indicator=True flags left_only/right_only/both; concat stacks frames by row or column.
