Merge DataFrames with Different Join Types
Pandas data engineering interview problem. Difficulty: beginner. Pattern: Merges. About 12 minutes. Free to practice.
Demonstrate inner/left/right/outer merges stacked with a join_type column. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
A merge (join) combines 2 tables on a shared column, and the type of join decides which rows survive. You will compare the four types side by side. In the editor, df1 holds users and their spend (users 1, 2 and 3), and df2 holds users and their segment (users 2, 3 and 4). Merge the two on user_id 4 times, once with each join type: inner, left, right and outer. Add a column called join_type to each result that says which join made it, then stack all four results into one table. Sort by join_type and then by user_id. Save the final table in result.
Requirements
- Merge df1 and df2 on user_id with each of the 4 join types.
- Add a join_type column with the values inner, left, right and outer.
- Stack the four results into one DataFrame with pd.concat.
- Sort by join_type and then by user_id.
Constraints
- df1 has user_id and spend. df2 has user_id and segment.
- All four join_type values must appear in the output.
- Rows with no match on the other side keep NULL (NaN or None) in the missing columns.
Examples
Input: df1/df2 Output: user_id | spend | segment | join_type 2 | 20.0 | A | inner 3 | 30.0 | B | inner 1 | 10.0 | None | left 2 | 20.0 | A | left 3 | 30.0 | B | left 2 | 20.0 | A | outer 3 | 30.0 | B | outer 1 | 10.0 | None | outer 4 | None | C | outer 2 | 20.0 | A | right 3 | 30.0 | B | right 4 | None | C | right Each how produces a different null pattern; exact row order follows sort.
Topics: lakebench, pandas, merge, joins.
More interview problems · All interview problems · Learn data engineering
Merge DataFrames with Different Join Types
Interview-style drill: Demonstrate inner/left/right/outer merges stacked with a join_type column.
Merge `df1` and `df2` on `user_id` with how in {inner,left,right,outer}. Concat the four results with a `join_type` column. Sort by `join_type`, `user_id`. Assign `result`.