We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Merging on Different Keys

Sometimes the key columns you want to use in a merge have different names across tables, so a simple on="column" isn't enough. One table might call the key prod_id while another calls it id.

sales = pd.DataFrame({"prod_id": ["CHL-482", "TST-731"], "quantity": [10, 20]})
products = pd.DataFrame(
    {"id": ["CHL-482", "TST-731"], "name": ["ChillVault Mini", "ToastForge Pro"]}
)

Use left_on and right_on to tell Pandas which columns should be matched up:

result = pd.merge(sales, products, left_on="prod_id", right_on="id", how="left")
print(result)
#    prod_id  quantity       id             name
# 0  CHL-482        10  CHL-482  ChillVault Mini
# 1  TST-731        20  TST-731   ToastForge Pro

Notice that both prod_id and id are in the result! They're redundant, so it's common practice to drop one:

result = result.drop(columns="id")

You'll see this pattern constantly in database work. Real systems are far from guaranteed to use the same column names across tables.

Assignment

SnackStack's sales data uses transaction_id, while the transaction details table calls the same key id. The weekend sales report needs both tables merged without leaving duplicate key columns behind.

Complete the merge_transactions function. It accepts two DataFrames: sales and transactions. It should: