Sub topic 1
Merging and Joining DataFrames in pandas
Prerequisites
This chapter assumes you know basic Python, can create and select from pandas DataFrames, understand the DataFrame index, and recognize common pandas data types.
Keys and how tables relate
A key is a column whose values identify related rows in different tables. For example, customer_id connects a customer table to an order table. The customer table usually has one row per customer. The order table can have several rows for one customer.
This relationship is called one-to-many: one customer can have many orders. A merge matches key values and copies columns from both tables into one result.
Your first merge
DataFrame.merge combines tables using a shared column. By default, it performs an inner join, which keeps only keys found in both tables.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Chen"],
})
orders = pd.DataFrame({
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 3, 4],
"amount": [25.0, 40.0, 15.5, 60.0],
})
result = customers.merge(orders, on="customer_id")
print(result)Customer 1 appears twice because that customer has two orders. Chen appears once. Ben is absent because no order matches customer 2. Order 13 is absent because customer 4 is not in customers.
Inner, left, right, and outer joins
The how argument controls which unmatched rows survive.
| Join type | Rows kept |
|---|---|
| `inner` | Matching keys in both tables |
| `left` | Every row from the left table |
| `right` | Every row from the right table |
| `outer` | Every row from both tables |
Use left when the left table is your main list and related data is optional. Use outer when you need to audit differences between tables. Missing values appear as NaN.
left = customers.merge(orders, on="customer_id", how="left")
outer = customers.merge(orders, on="customer_id", how="outer")
print(left)
print(outer)A right join is equivalent to swapping the tables in a left join. Choose the form that makes the intended primary table clearest.
> callout note > Check key uniqueness before merging. Duplicate keys can multiply rows and produce a result much larger than either input.
Exercise
Which join keeps every customer, including customers without orders?
Show answer
A left join with customers as the left DataFrame: customers.merge(orders, on="customer_id", how="left").