Sub topic 2
Your first merge
What you need before starting
This chapter assumes you can build a DataFrame and select columns in pandas. It also assumes you know what the index is and have seen common dtypes such as int64, float64, and object. You do not need to know anything about joins yet. The chapter before this one introduced keys. Here you use them for the first time.
By the end you will be able to:
- Write a merge with
pd.mergeand withDataFrame.merge. - Predict which rows survive the default merge.
- Read the shape of the result: its columns, its row count, and its index.
- Recognize the two errors beginners hit most often.
What a merge does
A merge combines two DataFrames by matching values in a key column. For each row in the left table, pandas looks for rows in the right table that have the same key value. Each match produces one output row, containing the left row's columns followed by the right row's columns.
This is the same operation as a SQL JOIN. If you know SQL, merge is INNER JOIN ... ON by default.
The data below is used throughout the chapter. customers has one row per customer. orders has one row per order, and customer_id says who placed it.
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)The output is:
customer_id name order_id amount
0 1 Ana 10 25.0
1 1 Ana 11 40.0
2 3 Chen 12 15.5Look at what happened to each input row:
- Ana (customer 1) has two orders, so her row appears twice. Her name is copied into both output rows.
- Chen (customer 3) has one order, so he appears once.
- Ben (customer 2) has no orders. His row is gone.
- Order 13 belongs to customer 4, who is not in
customers. That order is gone too.
The default behavior keeps only keys found in both tables. That is why it is called an inner merge.
Two ways to call it
pandas offers the same operation in two forms. They give identical results.
# Method form: the DataFrame you call it on is the left table
a = customers.merge(orders, on="customer_id")
# Function form: both tables are arguments
b = pd.merge(customers, orders, on="customer_id")
print(a.equals(b))This prints True.
Use the method form when you are chaining operations, because it reads left to right. Use the function form when neither table is a natural "main" table, or when you want the two inputs to look symmetrical in the code.
In both forms the first table is the left table and the second is the right table. This matters for column order, row order, and for the other join types you will meet in the next chapter.
The main arguments
You will use these arguments constantly. Pass them as keywords, which is clearer than relying on position.
| Argument | Meaning | Default |
|---|---|---|
| `right` | The second DataFrame (for the method form) | required |
| `on` | Column name, or list of names, present in both tables | common column names |
| `how` | Which rows to keep: `inner`, `left`, `right`, `outer`, `cross` | `inner` |
Other arguments (left_on, right_on, suffixes, validate, indicator) get their own chapters.
Leaving out `on`
If you omit on, pandas uses every column name that appears in both tables.
print(customers.merge(orders))Here the only shared column is customer_id, so the result matches the earlier one. This is convenient, but fragile. If someone later adds a name column to orders, the merge silently starts matching on customer_id and name together. Naming the key with on makes the code say what it means.
What the result looks like
Four properties of the result are worth knowing exactly.
- Columns. The key column appears once, not twice. The left table's other columns come next, then the right table's other columns.
- Row count. It is not the row count of either input. It is the number of matching pairs. Ana's one row matched two order rows, so she produces two output rows.
- Row order. An inner merge keeps the order of the left table's keys. Within one key, the right table's rows appear in their original order.
- Index. When you merge on columns, the input indexes are ignored and discarded. The result gets a fresh
RangeIndexstarting at 0. If your original index carried meaning, such as an ID or a date, move it into a column withreset_index()before merging, or use an index-based join (a later chapter).
You can confirm the row count and index directly:
print(len(result))
print(result.index.tolist())
print(result.dtypes)len(result) is 3, the index is [0, 1, 2], and dtypes shows that customer_id, order_id are int64, name is object (or str in recent pandas versions with the new string dtype), and amount is float64.
Merging a filtered or selected table
You rarely need every column from the right table. Select the columns you want before merging, and always include the key.
big_orders = orders.loc[orders["amount"] > 20, ["customer_id", "amount"]]
print(customers.merge(big_orders, on="customer_id"))This produces two rows for Ana's orders over 20 (25.0 and 40.0). Chen's order of 15.5 is filtered out before the merge, so Chen has no match and disappears. Filtering before the merge changes which keys exist on the right side, so it changes which left rows survive. If you want to keep every customer, you need a left merge, covered in the next chapter.
Selecting columns first also reduces memory use, because pandas does not copy columns you did not ask for.
Common errors
KeyError: the key column is missing
try:
customers.merge(orders, on="cust_id")
except KeyError as err:
print("KeyError:", err)This prints KeyError: 'cust_id'. The name given to on must exist as a column in both tables. Check spelling, capitalization, and stray whitespace in the column names with print(df.columns.tolist()). If the key has different names in the two tables, on cannot express that. The next chapter shows left_on and right_on.
MergeError: nothing to match on
other = pd.DataFrame({"sku": [1, 2], "price": [1.5, 12.0]})
try:
customers.merge(other)
except pd.errors.MergeError as err:
print("MergeError:", err)With no on and no shared column names, pandas has no way to choose a key. The message begins with No common columns to perform merge on. Fix it by naming the keys explicitly.
Rows vanish without any error
This is the most dangerous case, because nothing fails. The default inner merge removes unmatched rows quietly. In the example, 3 customers and 4 orders went in, and 3 rows came out. Two of the originals were dropped and nothing warned you.
A quick manual check is to ask which keys did not make it through:
lost_customers = customers[~customers["customer_id"].isin(orders["customer_id"])]
lost_orders = orders[~orders["customer_id"].isin(customers["customer_id"])]
print(lost_customers)
print(lost_orders)The first result is Ben's row. The second is order 13. The ~ operator negates the boolean mask, so the filters select rows whose key is not found on the other side.
Choosing between the two forms in practice
A merge is a good fit when the two tables describe different things, such as customers and orders, and a shared key connects them. It is the wrong tool when the tables describe the same kind of thing and you want more rows. That case is pd.concat, covered in a later chapter.
A short checklist before writing a merge:
- Which column identifies the same entity in both tables?
- Does that column have the same dtype in both tables? A
int64key will not match anobjectkey holding strings like"1". - Can a key value appear more than once in either table? If so, rows multiply, as they did for Ana.
- Which unmatched rows are you willing to lose?
Answer these before running the merge, and you will rarely be surprised by the output.
Exercise
Using the customers and orders tables from this chapter, you run customers.merge(orders, on="customer_id") and get 3 rows. Your colleague adds a fifth order to orders for customer 2 (Ben) and reruns it. How many rows does the result have now, which row appears first, and why does the result's index start at 0 even though the tables' indexes were also 0-based?
Show answer
The result has 4 rows. Ben now has one matching order, so he appears once, between Ana's two rows and Chen's row, because an inner merge keeps the order of the left table's keys (1, 1, 2, 3). Ana's row is first. The index starts at 0 because merging on columns discards the input indexes and builds a new RangeIndex over the result rows. It would start at 0 even if the inputs had used different index labels.
Exercise
What happens if you call customers.merge(orders, on="customer_id") when orders["customer_id"] holds the strings "1", "1", "3", "4" instead of integers? Would you get an error, an empty result, or the normal result? How would you check for it?
Show answer
You get an empty DataFrame (or, in some pandas versions, a ValueError complaining about merging int64 and object columns). Integers and strings never compare equal, so no key matches and the inner merge keeps nothing. Check with customers["customer_id"].dtype and orders["customer_id"].dtype, then convert with orders["customer_id"].astype("int64") before merging.