Joins & merges
Matching rows by key is easy. The interesting part is what happens to the rows that do not match.
Before you start
You almost never have all your data in one table. Customers live in one table, orders in another; products here, categories there. **Joining** (also called merging) is the operation that stitches related tables together on a shared key.
The interesting part is not what happens to rows that match — everyone expects those to end up combined. The interesting part is what happens to rows that don't match: inner join drops them, left join keeps the left side, outer join keeps everything and fills gaps with NaN.
This lesson watches customers meet orders under each of the four join types, so you can see exactly which rows survive and which disappear.
orders (left)
4 rows · cust_id is the key| Row | order_id | cust_idjoin key | amount |
|---|---|---|---|
| 1 | 10 | 50 | |
| 2 | 11 | 70 | |
| 3 | 12 | 30 | |
| 4 | 11 | 90 |
customers (right)
3 rows · one row per customer| Row | cust_idjoin key | name |
|---|---|---|
| 10 | Ana | |
| 11 | Ben | |
| 13 | Dee |
Every join question reduces to: what should happen to 12 and 13?
Step 1 of 6. Two frames, one shared key. `orders` has four rows; `customers` has three. They share the `cust_id` column, which is what a join matches on. Look at the keys before joining: orders reference customers 10, 11, 12 and 11 again. Customers lists 10, 11 and 13. Customer 12 has no record, and customer 13 has no orders.
Step 01 / 06
Two frames, one shared key
orders has four rows; customers has three. They share the cust_id column, which is what a join matches on.
Look at the keys before joining: orders reference customers 10, 11, 12 and 11 again. Customers lists 10, 11 and 13. Customer 12 has no record, and customer 13 has no orders.
import pandas as pdorders = pd.DataFrame({ "order_id": [1, 2, 3, 4], "cust_id": [10, 11, 12, 11], "amount": [50, 70, 30, 90],})customers = pd.DataFrame({ "cust_id": [10, 11, 13], "name": ["Ana", "Ben", "Dee"],})pd.merge(orders, customers, on="cust_id", how="inner")pd.merge(orders, customers, on="cust_id", how="left")pd.merge(orders, customers, on="cust_id", how="outer")orders.merge(customers, on="cust_id", how="left", indicator=True)