Sample DataFrame context
Orders and customers DataFrames with customer_id keys.
Syntax or pattern
orders.merge(customers, on="customer_id", how="left")5 practical examples
Join orders to customers
Bring customer details into an orders table.
orders_with_customers = orders.merge(customers, on="customer_id", how="left")Each order keeps its row and receives matching customer fields.
Join on different column names
Match tables when key names are different.
result = orders.merge(products, left_on="product_id", right_on="id", how="left")The order rows receive product data even when key columns have different names.
Check unmatched rows
Use indicator to find records with no match.
merged = orders.merge(customers, on="customer_id", how="left", indicator=True)
unmatched = merged[merged["_merge"] == "left_only"]The unmatched table shows customer IDs missing from the lookup table.
Avoid duplicated joins
Check duplicated keys before merging.
customers[customers["customer_id"].duplicated()]This helps detect lookup keys that could duplicate order rows after the join.
Join multiple lookup tables
Add customer and product details in steps.
report = (orders
.merge(customers, on="customer_id", how="left")
.merge(products, on="product_id", how="left"))The final report includes order, customer and product fields.
Common mistakes to avoid
- Changing the original DataFrame before checking the result.
- Forgetting to inspect row counts before and after the operation.
- Using a pattern without confirming column names and data types.
FAQ
What is the main use of merge Examples?
Join sales, customers, products and lookup tables with keys.
Should I use this in a notebook or a script?
Both work. Use a notebook while exploring the data, then move the final workflow into a repeatable script when it is stable.
How do I avoid breaking my source data?
Create a copy of the DataFrame before transforming it and check row counts, missing values and sample rows after each important step.