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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
