Merging, Joining and Reshaping
Combine tables with merge and concat, choose between inner, left and outer joins, check row counts for duplicates, and reshape data between wide and long.
Welcome back!
Step 1 of 12Learn
Combining tables with merge
Real data rarely lives in one table. Rentals record a station ID; station names, capacities and neighborhoods live in a separate stations table. merge combines them on a shared key, like a SQL join:
rentals = pd.DataFrame({"station_id": [1, 2, 1, 4], "bikes_out": [14, 9, 6, 7]})
stations = pd.DataFrame({"station_id": [1, 2, 3], "name": ["Harbor", "Market", "Park"]})
merged = rentals.merge(stations, on="station_id", how="left")
# station_id bikes_out name
# 0 1 14 Harbor
# 1 2 9 Market
# 2 1 6 Harbor
# 3 4 7 NaNThe how argument decides which rows survive:
- inner (the default): only keys found in both tables. Rental 4 and station 3 disappear.
- left: every row of the left table; unmatched ones get NaN for the right table's columns. Rental 4 stays with a missing name.
- right: every row of the right table.
- outer: every row from both, with NaN where there's no match.
If the key columns have different names, use left_on="station_id", right_on="id". The indicator=True option adds a _merge column showing whether each row matched in both, left_only or right_only, which is extremely useful for checking a join.
Step 2 of 12Compare
Join types for rentals (left) and stations (right)
| Aspect | Keeps | Rows from the example |
|---|---|---|
| inner | Only keys present in both tables | 3 (rental 4 and station 3 dropped) |
| left | All left rows, matched where possible | 4 (rental 4 has a NaN name) |
| right | All right rows, matched where possible | 4 (Harbor twice, Market, and Park with NaN bikes) |
| outer | Everything from both sides | 5 (all rentals plus Park) |
Step 3 of 12Practice · Work it out
A customers table has 1,000 rows, one per customer. An orders table has 4,200 rows, and 50 orders belong to customer IDs that are not in the customers table. How many rows does orders.merge(customers, on="customer_id", how="inner") return?
Step 4 of 12Learn
The row-count check that saves reports
The most dangerous merge bug produces no error at all: duplicate keys multiply rows.
Suppose the stations table accidentally lists station 1 twice, once with an old name and once with a new one. Every rental at station 1 now matches two station rows, so each such rental appears twice in the merged result. Totals computed afterwards, such as total bikes out, are inflated, and nothing warns you.
Defensive habits:
- Check key uniqueness before merging:
stations["station_id"].is_uniqueshould be True for a lookup table. - Compare row counts before and after. A left join onto a lookup table should return exactly as many rows as the left table had.
- Let pandas enforce it:
rentals.merge(stations, on="station_id", how="left", validate="many_to_one")raises an error if the right side's keys aren't unique. - Inspect unmatched rows with
indicator=Trueto find typos in keys, mismatched types (an ID stored as int in one table and as text in the other never matches) or missing reference data.
Relationship types worth naming: one-to-one (each key appears once on each side), many-to-one (many rentals per station; the typical lookup) and many-to-many (both sides repeat keys; usually a sign that something is wrong or that the join needs another key).
Step 5 of 12Practice · What would you do?
What would you do?
After merging 10,000 sales rows with a product table using a left join, Sam gets 10,340 rows, and total revenue is 3% higher than finance reports. What's the most likely cause?
Step 6 of 12Practice · Code challenge · Python
Implement a left join in plain Python. Write left_join(left, right, key) where both are lists of dictionaries and right has unique keys. Return a new list with one dictionary per row of left, containing the left row's fields plus the matching right row's fields. If there's no match, add only the left fields. Keep the order of left.
left_join([{"id": 1, "b": 14}, {"id": 4, "b": 7}], [{"id": 1, "name": "Harbor"}, {"id": 2, "name": "Market"}], "id")len(left_join([{"id": 1}, {"id": 1}, {"id": 2}], [{"id": 1, "n": "A"}, {"id": 2, "n": "B"}], "id"))left_join([{"id": 2, "b": 9}], [{"id": 2, "name": "Market"}], "id")[0]["name"]
Step 7 of 12Learn
Stacking tables and reshaping
pd.concat stacks tables instead of matching them. Monthly files with the same columns become one table:
all_months = pd.concat([jan, feb, mar], ignore_index=True)ignore_index=True builds a fresh 0..n index; without it, you'd get repeated labels from each file. Concatenating side by side uses axis=1, but merge is usually the safer choice when rows must line up by a key.
Data also comes in two shapes:
- Wide: one row per entity, one column per measurement:
station, jan, feb, mar. - Long (or "tidy"): one row per observation:
station, month, bikes.
Long format is what grouping, plotting libraries such as seaborn, and most models expect. Wide format is often nicer for humans and reports.
long = wide.melt(id_vars="station", var_name="month", value_name="bikes")
wide_again = long.pivot(index="station", columns="month", values="bikes")melt turns columns into rows; pivot turns rows into columns. A wide table of 3 stations × 12 month columns becomes a long table of 36 rows. pivot fails if any station-month pair appears twice; pivot_table with an aggfunc handles duplicates by aggregating them.
Step 8 of 12Practice · Work it out
A wide table has 25 rows (one per store) and the columns store plus 12 month columns. After melt(id_vars="store", var_name="month", value_name="sales"), how many rows does the long table have?
Step 9 of 12Learn
Keys that refuse to match
Sometimes a merge returns far fewer matches than expected, or none at all, with no error. The keys look identical on screen but aren't identical to the computer. The usual suspects:
- Different types. One table stores
station_idas the integer 7, the other as the string "7". They never match. Checkdf.dtypeson both sides and convert one. - Whitespace and case. "Harbor " with a trailing space, or "harbor" in lowercase, won't match "Harbor". Apply
.str.strip()and a consistent case to text keys before joining. - Leading zeros. "007" and "7" differ as strings; the fix depends on which form the source system treats as correct.
- Different granularity. Joining daily sales to monthly targets needs a shared month key on both sides, not a date on one and a month on the other.
- Genuinely missing reference data. New stations that the lookup table doesn't list yet.
The indicator=True option shows exactly which rows failed to match, and value_counts() on the _merge column summarizes it. Looking at a handful of unmatched keys from each side usually reveals the cause within minutes.
Step 10 of 12Note
Step 11 of 12Practice · Select all that apply
A left merge of rentals onto stations leaves the station name missing for most rows. Which are plausible causes? Select all that apply.
Select all that apply.
Step 12 of 12Practice · True or false
If a lookup table used on the right side of a left merge contains duplicate keys, the merged result can have more rows than the left table.
Lesson complete!