Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 12/ 160
01. Python & Data Wrangling

Merging, Joining & Concatenating Data

Combine tables with merge/join/concat, handle many-to-many fanout, and validate keys.

Intermediatemerge · join types3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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 _merge column showing left_only, right_only or both.
Fan-out
A join that multiplies rows because the other side has duplicate keys.

Visual diagram

Loading interactive 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.

Enriching orders with customer attributes

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.

Key takeaway: Left merge to enrich, clean keys first, control suffixes, and validate the relationship.

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.

Concatenating monthly files with provenance

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.

Key takeaway: Validate relationships, reconcile counts, and concat once with provenance.

How it works, step by step

Step 1 of 4
Prepare

1. Check keys on both sides

Match dtypes, strip and standardise strings, and test uniqueness where you expect it.

customers.customer_id.is_unique
Key numbers at this step
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

merge
Best for: Attaching attributes by key

Strengths: Flexible keys and join types; validation options.

Watch out: Easy to fan out or lose rows without checks.

join
Best for: Index-aligned frames

Strengths: Short syntax.

Watch out: Depends on index state; less explicit.

concat
Best for: Stacking same-shaped frames (files, months)

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?
Interview tip: Say "I validate the key relationship and reconcile row counts". Those two habits are what interviewers expect from someone who has merged real data.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Merging, Joining & Concatenating Data with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
GroupBy, Aggregations & Pivot Tables
Next topic
Date & Time Manipulation