Python / Data Science Essentials Interview Questions
How do you merge and join DataFrames in Pandas, and what do the different join types mean?
Real-world data lives in multiple tables. Pandas merge() implements SQL-style joins, and concat() stacks DataFrames. Choosing the right join type prevents silently losing or duplicating rows.
| how= | Keeps rows from | Missing matches become |
|---|---|---|
| 'inner' | Both DataFrames (intersection) | NaN (none dropped because only matched) |
| 'left' | All of left, matched from right | NaN in right columns |
| 'right' | All of right, matched from left | NaN in left columns |
| 'outer' | Both (union) | NaN on whichever side has no match |
import pandas as pd customers = pd.DataFrame({ 'cust_id': [1, 2, 3, 4], 'name': ['Alice', 'Bob', 'Carol', 'Dave'], }) orders = pd.DataFrame({ 'order_id': [101, 102, 103], 'cust_id': [1, 2, 9], # cust_id 9 has no match; Dave has no order 'amount': [200, 150, 80], }) # Inner join â only rows that match in both pd.merge(customers, orders, on='cust_id', how='inner') # 2 rows # Left join â all customers, NaN where no order pd.merge(customers, orders, on='cust_id', how='left') # 4 rows # Different key names in each table pd.merge(customers, orders, left_on='cust_id', right_on='cust_id') # same here, but shows syntax # Merge on index pd.merge(customers.set_index('cust_id'), orders, left_index=True, right_on='cust_id') # concat â stack vertically (rows) or horizontally (columns) pd.concat([df1, df2], axis=0, ignore_index=True) # stack rows pd.concat([df1, df2], axis=1) # add columns side by side
More Related questions...