Skip to content
Codescope

Joins & merges

Matching rows by key is easy. The interesting part is what happens to the rows that do not match.

core10 min6 steps

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
Roworder_idcust_idjoin keyamount
11050
21170
31230
41190

customers (right)

3 rows · one row per customer
Rowcust_idjoin keyname
10Ana
11Ben
13Dee

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.

01 / 06

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.

analysis.pyPython
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)