Sub topic 10
Replacing per-row lookups with map and merge
This chapter assumes you can write a Python loop and dictionary, build and index a DataFrame, and have read the earlier chapters on column arithmetic and index alignment. Here you replace the common "look up each row's value somewhere else" loop with Series.map and DataFrame.merge.
The per-row lookup pattern
A lookup attaches information from a reference source, such as a rate per store, a region per customer, or a price per product code, to every row of a table. The loop version looks like this:
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b", "c"],
"amount": [10, 30, 5, 15, 8],
})
rates = {"a": 0.10, "b": 0.20}
taxes = []
for _, row in sales.iterrows():
rate = rates.get(row["store"])
taxes.append(row["amount"] * rate if rate is not None else None)
sales["tax_loop"] = taxes
print(sales)This loop pays twice. It builds a Series for every row, as an earlier chapter showed. It also runs the dictionary lookup in interpreted Python once per row. map and merge move both steps into pandas' compiled code, which hashes the keys once and matches whole columns together.
Series.map with a dictionary
Series.map takes a dictionary and replaces each value in the column with the dictionary's value for that key. The result is a new Series with the same index as the original, so you can assign it straight back.
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b", "c"],
"amount": [10, 30, 5, 15, 8],
})
rates = {"a": 0.10, "b": 0.20}
sales["rate"] = sales["store"].map(rates)
sales["tax"] = sales["amount"] * sales["rate"]
print(sales)Store "c" is not in the dictionary, so its rate and tax are NaN. map never raises an error for a missing key. The NaN also turns an integer-valued result into float64. Decide what a missing key should mean and handle it explicitly:
sales["rate"] = sales["store"].map(rates).fillna(0.0)Use a default only when it is correct for the business rule. Often you want the missing keys to stay visible. You can count them with sales["store"].map(rates).isna().sum() before you fill anything.
Mapping with a Series
map also accepts a Series. It then matches each value against the Series' index.
rate_series = pd.Series({"a": 0.10, "b": 0.20})
sales["rate"] = sales["store"].map(rate_series)The index of the lookup Series must be unique. With duplicate labels, pandas cannot choose one value per key and raises an error. A dictionary has unique keys by construction, so it can't fail this way.
map is not replace
Series.replace leaves values it does not find unchanged. map turns them into NaN. If you use map on a column of codes and some codes are absent from the dictionary, you lose those values instead of keeping them. To keep unmatched values, combine the two steps:
codes = pd.Series(["NY", "CA", "TX"])
names = {"NY": "New York", "CA": "California"}
print(codes.map(names).fillna(codes))Passing a function to map
map also accepts a function. That form calls the function once per element in a Python loop, so it is no faster than your own loop. Prefer the dictionary or Series form whenever the lookup data can be written as a table.
Merge for lookup tables
A dictionary holds one value per key. When the reference data has several columns, or the match needs several keys, store it as a DataFrame and use merge.
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b", "c"],
"amount": [10, 30, 5, 15, 8],
})
stores = pd.DataFrame({
"store": ["a", "b"],
"region": ["north", "south"],
"rate": [0.10, 0.20],
})
merged = sales.merge(stores, on="store", how="left", validate="many_to_one")
merged["tax"] = merged["amount"] * merged["rate"]
print(merged)Three arguments matter here:
on="store"names the key column that exists in both tables.how="left"keeps every row ofsales, in its original order. Unmatched rows getNaNin the new columns. The default,how="inner", silently drops them.validate="many_to_one"checks that the key is unique in the right-hand table and raises an error if it is not.
Duplicate keys multiply rows
The most damaging merge error is duplicate keys in the lookup table. Every left row then matches every duplicate, and the result has more rows than the input.
import pandas as pd
sales = pd.DataFrame({
"store": ["a", "a", "b", "b", "c"],
"amount": [10, 30, 5, 15, 8],
})
stores = pd.DataFrame({
"store": ["a", "b"],
"rate": [0.10, 0.20],
})
stores_dup = pd.concat([stores, stores.iloc[[0]]], ignore_index=True)
print(len(sales.merge(stores_dup, on="store", how="left"))) # 7, not 5
try:
sales.merge(stores_dup, on="store", how="left", validate="many_to_one")
except pd.errors.MergeError as exc:
print("caught:", exc)The unchecked merge returns 7 rows. Store "a" appears twice in sales and twice in the lookup, which gives 4 rows. A total computed afterwards would be wrong, and nothing would warn you. Passing validate turns that silent error into an exception, so add it to every lookup merge.
Different column names and several keys
When the key columns have different names, use left_on and right_on. Both columns are kept, so drop the redundant one afterwards. When the match needs several columns, pass a list.
import pandas as pd
orders = pd.DataFrame({
"shop_id": [1, 1, 2],
"month": ["2026-01", "2026-02", "2026-01"],
"units": [5, 7, 3],
})
prices = pd.DataFrame({
"id": [1, 1, 2],
"month": ["2026-01", "2026-02", "2026-01"],
"price": [2.5, 2.75, 3.0],
})
out = orders.merge(
prices,
left_on=["shop_id", "month"],
right_on=["id", "month"],
how="left",
validate="many_to_one",
).drop(columns="id")
out["revenue"] = out["units"] * out["price"]
print(out)Choosing between map and merge
| Question | map | merge |
|---|---|---|
| Number of columns to bring in | One | One or many |
| Number of key columns | One | One or several |
| Lookup source | Dictionary or Series | DataFrame |
| Index of the result | Same as the input | New default index |
| Missing key | `NaN` | `NaN` with `how="left"`; row dropped with the default `how="inner"` |
| Duplicate keys in the lookup | Error for a Series; impossible for a dict | Rows multiply unless you use `validate` |
The index row is the one that bites during assignment. map returns a Series aligned to the original rows, so df["x"] = df["k"].map(d) is safe even when df has a custom index. merge returns a new DataFrame with a fresh RangeIndex, so assigning a merged column back into a DataFrame with a different index lines up on the wrong labels. Keep working with the merged frame, or call set_axis(df.index) on it only after you have confirmed the row order is unchanged.
Key dtypes must agree
Both map and merge compare keys by value and type. The two functions respond differently when the types do not match.
import pandas as pd
ids = pd.Series([1, 2, 3])
print(ids.map({"1": "x", "2": "y"}).tolist()) # [nan, nan, nan]
left = pd.DataFrame({"id": [1, 2, 3]})
right = pd.DataFrame({"id": ["1", "2"], "label": ["x", "y"]})
try:
left.merge(right, on="id", how="left")
except ValueError as exc:
print("caught:", exc)map returns all NaN without a warning, because the integer 1 is not the string "1". merge refuses to join an integer column to a string column and raises a ValueError. Check left["id"].dtype and right["id"].dtype before you debug anything else. Convert one side with astype, or clean the keys first with the .str accessor. Stray whitespace and different capitalisation also stop keys from matching.
Measuring the gain
As in the earlier timing chapter, check equivalence before you time.
import timeit
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
keys = [f"s{i}" for i in range(1000)]
rates = {k: 0.01 * (i % 20) for i, k in enumerate(keys)}
big = pd.DataFrame({
"store": rng.choice(keys, size=100_000),
"amount": rng.integers(1, 100, size=100_000),
})
def with_loop(frame):
out = []
for store in frame["store"]:
out.append(rates[store])
return pd.Series(out, index=frame.index)
def with_map(frame):
return frame["store"].map(rates)
assert np.array_equal(with_loop(big).to_numpy(), with_map(big).to_numpy())
print(timeit.timeit(lambda: with_loop(big), number=5))
print(timeit.timeit(lambda: with_map(big), number=5))The baseline here iterates over a single column instead of using iterrows, so it is already the faster kind of loop. The map version should still win, and the gap grows with the number of rows. The exact figures depend on your machine and pandas version.
Other lookup forms and their limits
- Lookup by index label. If the reference data is a Series indexed by key,
rate_series.reindex(sales["store"]).to_numpy()returns one value per row, withNaNfor missing keys..loc[sales["store"]]does the same job, but raises aKeyErrorwhen a key is missing, and its result carries the keys as its index instead of the original row index. - Lookups that depend on a range. A lookup such as "which price band contains this amount?" is not an exact match. Use
pd.cutwith bin edges orpd.merge_asofon sorted keys. Neithermapnor a plainmergefits. - Lookups that depend on the previous result. If each row's lookup depends on the result of the row before it, you are in the territory covered by the shift and cumulative chapter, or by the final chapter on loops that cannot be vectorised.
Exercises
Exercise
A column code holds integers, and you call df["code"].map(names) where the keys of names are strings such as "101". Every result is NaN and no error is raised. Why, and how do you fix it?
Show answer
The keys are compared by value and type, and the integer 101 is not equal to the string "101". map does not warn about unmatched keys. Convert the column with df["code"].astype(str).map(names), or convert the dictionary keys to integers. Then count the NaN results to confirm they are gone.
Exercise
orders has 1000 rows. After orders.merge(customers, on="customer_id", how="left") the result has 1040 rows. What is the most likely cause, and which argument would have caught it?
Show answer
The customers table has duplicate customer_id values. Each order for such a customer matches every duplicate row, which adds rows. Passing validate="many_to_one" makes merge raise a MergeError instead. Fix it by removing the duplicates, for example with customers.drop_duplicates("customer_id"), once you have checked which duplicate row is the correct one.
Exercise
You write df["region"] = df.merge(regions, on="zip", how="left")["region"], and df has a custom, non-sequential index. Why is this risky, and what is a safer way to write it?
Show answer
merge returns a frame with a new default index (0, 1, 2, ...). Assigning its column back aligns on index labels, so values land on the wrong rows, or on NaN, wherever df's labels differ. If the lookup is a single column with unique keys, use df["region"] = df["zip"].map(regions.set_index("zip")["region"]), which keeps the original index. If you need merge, keep working on the merged frame.