PY-401 ยท Summarising and joining
merge and join
โฑ 9 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
merge combines two tables by matching values in a shared column, like a SQL JOIN or an Excel VLOOKUP. orders.merge(customers, on="customer_id") adds each customer's name to their orders. how="inner" (the default) keeps only matches, how="left" keeps every row of the left table, and pd.concat stacks tables on top of each other.
- Join two tables on a key column
- Choose inner or left join
- Stack tables with concat
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import pandas as pdorders = pd.DataFrame({"order_id": [1, 2, 3, 4],"customer_id": [10, 20, 10, 30],"amount": [250, 90, 120, 400],})customers = pd.DataFrame({"customer_id": [10, 20, 40],"name": ["Asha", "Ben", "Dina"],})print(orders.merge(customers, on="customer_id"))print(orders.merge(customers, on="customer_id", how="left"))
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
order_id customer_id amount name
0 1 10 250 Asha
1 2 20 90 Ben
2 3 10 120 Asha
order_id customer_id amount name
0 1 10 250 Asha
1 2 20 90 Ben
2 3 10 120 Asha
3 4 30 400 NaN ๐ฏ Set report to scores merged with students on "student_id", keeping every score row even when the student is unknown.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
report = scores.merge(students, on="student_id", how="left")
- The problemThe orders table has customer numbers, and the customer table has names. The report needs names next to amounts. In Excel that is a VLOOKUP per row. In pandas it is one merge.
- The Python idea
left.merge(right, on="key")mergecombines two tables by matching values in a shared column, like a SQL JOIN or an Excel VLOOKUP. - In real lifeAn online shop merges the orders table with the products table on product_id to get each order's category, then groups by category for the weekly report.
Start with a question
The orders table has customer numbers, and the customer table has names. The report needs names next to amounts. In Excel that is a VLOOKUP per row. In pandas it is one merge.
Data lives in separate tables: orders, customers, products. Almost every real analysis joins two or more of them.
Explain it like I'm 10
Two lists: one says "ticket 10 ordered pizza", the other says "ticket 10 is Asha". Match the ticket numbers and you know Asha ordered pizza.
The technical explanation
left.merge(right, on="key") matches rows where the key is equal. Use left_on and right_on when the names differ.
how="inner" keeps only keys found in both tables. how="left" keeps every left row and fills NaN where the right table has no match. "right" and "outer" also exist.
An order for customer 30 disappears in an inner join because customer 30 is not in the customer table. A left join keeps it with NaN for the name.
pd.concat([a, b], ignore_index=True) stacks tables with the same columns, such as January and February exports.
| how= | Keeps | Like in SQL |
|---|---|---|
"inner" | Only keys in both tables | INNER JOIN |
"left" | Every left row, NaN where no match | LEFT JOIN |
"outer" | Every row from both | FULL OUTER JOIN |
Syntax
left.merge(right, on="key")
left.merge(right, on="key", how="left")
pd.concat([a, b], ignore_index=True) Real-world scenario
An online shop merges the orders table with the products table on product_id to get each order's category, then groups by category for the weekly report.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: apply and map โQuestions people ask
What is the difference between merge and join in pandas?
merge joins on columns and is the general tool. join is a shortcut that joins on the index by default. Both can do inner, left, right and outer joins.
How do I merge on columns with different names?
Use left_on and right_on, for example orders.merge(customers, left_on="cust", right_on="customer_id"). You can drop the extra key column afterwards.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between merge and join in pandas?
merge joins on columns and is the general tool. join is a shortcut that joins on the index by default. Both can do inner, left, right and outer joins.
beginner How do I merge on columns with different names?
Use left_on and right_on, for example orders.merge(customers, left_on="cust", right_on="customer_id"). You can drop the extra key column afterwards.
intermediate What does merge do?
Combines tables by matching a key column. merge matches rows on equal key values.
intermediate Which keeps every row of the left table?
how="left". A left join keeps all left rows.
Quick revision
Remember
- Join two tables on a key column
- Choose inner or left join
- Stack tables with concat
- After a merge, check the row count. If it grew, the key repeats on both sides.
validate="many_to_one"makes pandas raise an error instead of silently duplicating rows.
Syntax
left.merge(right, on="key")
left.merge(right, on="key", how="left")
pd.concat([a, b], ignore_index=True) Official documentation
- Merge, join, concatenate and compare (docs.python.org)