Sub topic 10
Replacing per-row lookups with map and merge
This chapter assumes you can build a DataFrame, use column arithmetic, and know what an index is. A lookup means finding a value for each row in some other table or dictionary. Loops do this one row at a time. map and merge do it for the whole column at once.
The loop you are replacing
A common pattern is to read a key from each row and look it up in a dictionary.
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b"],
"amount": [10, 30, 5, 15],
})
rates = {"a": 0.10, "b": 0.20}
taxes = []
for _, row in sales.iterrows():
taxes.append(row["amount"] * rates[row["store"]])
sales["tax_loop"] = taxesThis builds a Series for every row and does a Python dictionary lookup each time. The next sections remove both costs.
Series.map with a dictionary
Series.map takes a dictionary and replaces each value with the matching dictionary value. The result is a new Series with the same index as the original, so it can go straight into column arithmetic.
sales["rate"] = sales["store"].map(rates)
sales["tax"] = sales["amount"] * sales["rate"]A key that is missing from the dictionary becomes NaN. That behaviour is useful, because you can find unmatched values with isna().
unknown = sales[sales["rate"].isna()]map also accepts a Series. In that case it matches the column's values against the Series' index. A Series is a good choice when the lookup table is already in pandas.
rate_series = pd.Series({"a": 0.10, "b": 0.20})
sales["rate"] = sales["store"].map(rate_series)DataFrame.merge for several columns
map returns one value per key. If you need several columns from the lookup table, or the key is made of more than one column, use merge.
stores = pd.DataFrame({
"store": ["a", "b"],
"rate": [0.10, 0.20],
"region": ["north", "south"],
})
result = sales[["store", "amount"]].merge(stores, on="store", how="left")
result["tax"] = result["amount"] * result["rate"]how="left" keeps every row of sales, even when the store has no match. Unmatched rows get NaN in the new columns.
Choosing between map and merge
| Situation | Use |
|---|---|
| One value per key, lookup is a dict or Series | `map` |
| Several columns needed from the lookup table | `merge` |
| Key spans more than one column | `merge` with `on=[...]` |
| Row order and index must stay exactly as they are | `map` |
Pitfalls
Duplicate keys in the lookup table are the main danger with merge. If stores held two rows for store a, each sale for a would appear twice in the result. That silently inflates totals. The validate argument makes pandas raise an error instead.
result = sales.merge(stores, on="store", how="left", validate="many_to_one")merge also resets the index of its result. If you assign a merged column back to the original frame, the rows may no longer line up. Prefer working with the merged frame, or use map when you need the original index preserved. A map with a Series that has duplicate index values raises an error, which is a useful signal.
Keys must also have the same dtype on both sides. A key stored as integers in one table and strings in the other matches nothing, and every result becomes NaN.
Exercise
A DataFrame orders has a column code with values such as "x1" and "x2". A dictionary names maps each code to a product name. Write one line that adds a product column, and say how to list the rows whose code is not in the dictionary.
Show answer
orders["product"] = orders["code"].map(names). Missing codes become NaN, so orders[orders["product"].isna()] lists the unmatched rows.
Exercise
You run a left merge of 1,000 sales rows with a lookup table and get 1,040 rows back. What is the likely cause, and how do you make pandas catch it?
Show answer
The lookup table contains duplicate keys, so some sales rows matched more than one row. Pass validate="many_to_one" to merge so pandas raises an error.