Merging, Joining & Concatenating Data
Combine tables with merge/join/concat, handle many-to-many fanout, and validate keys.
In plain words
Merging lines up rows from two tables that share a key, and concatenating stacks tables on top of each other.
Think of it like…
Matching two lists of guests: one list has names and dietary needs, the other names and seats. If a name appears twice on one list, every combination appears; if a name is missing from one, the row either disappears (inner) or is kept with a blank (left).
Where you’ve seen it
Orders (1.2M rows) are merged with customers (400K rows) on customer_id. The result has 1.9M rows, not 1.2M, because the customer table has duplicate IDs from a failed deduplication. Adding validate="many_to_one" makes the code fail immediately with a clear error, the team dedupes customers, and the merged table returns to exactly 1.2M rows with the new columns attached.
Words you’ll hear
- Join type (how)
- inner keeps matches, left keeps all left rows, outer keeps everything, cross pairs every row.
- validate
- Asserts the key relationship (one_to_one, one_to_many, many_to_one) and raises if violated.
- indicator=True
- Adds a
_mergecolumn showing left_only, right_only or both. - Fan-out
- A join that multiplies rows because the other side has duplicate keys.
Visual diagram
Theory & deep dive
merge, join and the join types
merge joins on columns (on="customer_id", or left_on / right_on when names differ) and defaults to an inner join. Use how="left" to keep every row of the main table, which is usually what you want when enriching facts with attributes. Overlapping non-key column names get _x / _y suffixes; pass suffixes=("", "_cust") to control them. df.join(other) joins on the index and merge(left_index=True, right_on=...) mixes index and column keys.
Prepare keys first: strip whitespace and standardise case in strings, make dtypes match (an integer id and a string id never match), and remove or handle NaN keys, since NaN doesn't equal NaN in sensible ways. For time-based matches use pd.merge_asof (nearest earlier timestamp), and for non-equality conditions filter after a merge or use a cross merge on small tables.
out = orders.merge(customers[["customer_id", "segment", "city"]], on="customer_id", how="left", validate="many_to_one", indicator=True) then out["_merge"].value_counts() shows how many orders had no matching customer.
Validation, concat and reconciling row counts
A many-to-many merge multiplies rows. validate="one_to_one" | "one_to_many" | "many_to_one" | "many_to_many" raises MergeError when the relationship isn't what you declared; use it every time. Afterwards reconcile: after a left merge with a unique right key, len(result) == len(left); after an inner join, compare counts and inspect what was lost with an outer merge and indicator=True. To find unmatched rows, left[~left["customer_id"].isin(right["customer_id"])] is a clear anti-join.
pd.concat([jan, feb, mar], ignore_index=True) stacks monthly files; columns are aligned by name, missing ones become NaN, so check set(a.columns) == set(b.columns) and use join="inner" to keep only shared columns. axis=1 places frames side by side by index, which is easy to misalign. For many files, collect frames in a list and concat once; appending in a loop copies data repeatedly. Add a source column (pd.concat(dfs, keys=files, names=["file"])) so you can trace each row back to its file.
frames = {f.stem: pd.read_csv(f) for f in Path("exports").glob("*.csv")}; all_orders = pd.concat(frames, names=["file", "row"]).reset_index("file") stacks every file and keeps the source name in a column.
How it works, step by step
Step 1 of 41. Check keys on both sides
Match dtypes, strip and standardise strings, and test uniqueness where you expect it.
- NaN keys
- decide up front
When to use it & trade-offs
What it is
pd.merge(left, right, on="key", how="left") combines tables side by side on matching keys, like a SQL join; how can be inner, left, right, outer or cross. df.join is merge on the index. pd.concat([a, b]) stacks frames with the same columns (rows) or places them side by side (columns). The key safeguards are the validate= argument ("one_to_one", "many_to_one"...) and indicator=True, which catch duplicated keys and unmatched rows before they corrupt your numbers.
Why it matters: Combining tables is where silent bugs breed: a many-to-many join explodes 10,000 orders into 4 million rows, an inner join quietly drops customers with no match, and a merge on a key with different dtypes finds no matches at all. Validating joins and checking row counts is a professional habit, and it's the pandas version of the fan-out problem familiar from SQL.
When to reach for it
- Enriching events with customer or product attributes
- Stacking monthly exports into one table
- Finding unmatched records with an anti-join
When to avoid or be careful
- Merging on keys with different dtypes
- Many-to-many merges you didn't intend
- Appending to a DataFrame in a loop
Combining tables in pandas
Strengths: Flexible keys and join types; validation options.
Watch out: Easy to fan out or lose rows without checks.
Strengths: Short syntax.
Watch out: Depends on index state; less explicit.
Strengths: Fast, simple; keys track provenance.
Watch out: Mismatched columns create NaN; axis=1 can misalign.
Interview signals & numbers to know
When this topic comes up
- “The row count changed after the merge”
- “Merge returns no matches”
- “How do you combine monthly files?”
- Join types
- Fan-out
Benchmarks & rules of thumb
- 1.2M → 1.9M
- rows in the fan-out example
- validate=
- the one-line safeguard
- _merge
- indicator column values: left_only, right_only, both
Common mistakes & follow-ups
Common interview mistakes
- Joining a string id to an integer id and getting zero matches without an error.
- Using an inner join and losing customers with no orders from a report.
- Concatenating frames with slightly different column names, producing half-empty columns.
Likely interviewer follow-ups
- How do you detect and prevent row multiplication in a merge?
- What's the difference between merge and concat?
- How would you find orders with no matching customer?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Merging, Joining & Concatenating Data with data science interview Q&A and hands-on practice.