When to use pandas concat, merge or join to combine DataFrames, and how to keep them fast on large data
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Discuss the various methods for combining DataFrames (`concat`, `merge`, `join`) and their appropriate use cases, including performance considerations for large datasets.
```hint Appending or relating
Ask whether the frames hold more rows of the same kind of data or different facts about the same entities, and whether the keys live in columns or in the index.
```
```hint Where the time and memory go
Think about what each call copies, what happens to the row count when a key repeats on both sides, and how the key's dtype affects matching and hashing.
```
### What a Strong Answer Covers
- What `concat`, `merge` and `join` each do, including how they align labels and their default join types
- When each one fits: stacking like-shaped pieces, joining on key columns, joining on the index
- Correctness checks for a merge: cardinality, duplicate keys, unmatched rows and column name collisions
- Performance on large data: concatenating once, key dtypes and indexes, shrinking inputs before the join, and row explosion from many-to-many joins
- What to do when the join no longer fits comfortably in memory
### Follow-up Questions
- A left merge returned more rows than the left frame had. What happened, and how do you find the keys responsible?
- How would you write an anti-join (rows in one frame with no match in the other) in pandas?
- How would you attach to each trade the most recent quote at or before its timestamp?
- One table is 50 GB and the other is 200 MB. How would you join them?
Overview: Asks how pandas concat, merge and join differ, when each one is the right way to combine DataFrames, and how to keep them fast and correct on large datasets. Tests join semantics, cardinality checks and memory-aware pandas habits.