Sub topic 3
Mapping values with a dict or Series
This chapter covers Series.map when you pass a lookup table instead of a function. It assumes you can create a pandas Series and DataFrame, select columns, and assign new columns. It also assumes you know that a Python dict stores key-value pairs. The previous chapter covered map with a function. Here the argument is data, not code.
The working model
When the argument to map is a dict or a Series, pandas does not call anything. It treats the argument as a lookup table. For each element of the calling Series, it finds the element among the table's keys and returns the matching value. If no key matches, the result is NaN.
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.map({"a": "x", "b": "y"}))0 x
1 y
2 NaN
dtype: objectThe result has the same index and length as s. Only the values change. The key "c" is not in the dict, so its result is NaN. pandas does not raise an error and does not keep the original value.
The next diagram shows the lookup for a single element.
Why unmapped values become NaN
The NaN rule has two practical effects.
First, mapping can change the dtype. A Series of integers mapped through a dict that misses one value becomes float64, because integer columns cannot hold NaN.
import pandas as pd
s = pd.Series([1, 2, 3])
print(s.map({1: 10, 2: 20}))0 10.0
1 20.0
2 NaN
dtype: float64Second, a mapping that is incomplete by accident produces NaN values that are easy to miss. Check the result after you map:
import pandas as pd
s = pd.Series(["a", "b", "c"])
result = s.map({"a": "x", "b": "y"})
print(result.isna().sum())
print(s[result.isna()].unique())1
['c']The second line shows which input values had no match. For a mapping that must be complete, this is a cheap safety check.
Keeping the original value for unmapped items
map replaces everything. If you want to change only some values and leave the rest alone, you have two common options.
The first is to fill the gaps from the original Series:
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.map({"a": "x", "b": "y"}).fillna(s))0 x
1 y
2 c
dtype: objectThe second is Series.replace, which leaves unmatched values untouched:
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.replace({"a": "x", "b": "y"}))0 x
1 y
2 c
dtype: objectThe two are not identical. fillna(s) also restores the original value wherever the mapped result is NaN. That includes cases where your dict maps a value to NaN on purpose. replace only changes keys that are present and keeps the original value for the rest. Pick map when the table should cover every value, and replace when you are patching a few values.
A default for unmapped values
If you want a default other than NaN, pass a dict subclass that defines __missing__. The standard defaultdict does this.
from collections import defaultdict
import pandas as pd
grades = pd.Series(["A", "B", "D"])
table = defaultdict(lambda: "other", {"A": "top", "B": "good"})
print(grades.map(table))0 top
1 good
2 other
dtype: objectpandas detects the __missing__ method and uses it for keys that are not found. A plain dict has no such method, so it still produces NaN. Note that defaultdict adds each missing key to itself as a side effect. If you reuse the same object, it grows.
Mapping with a Series
A Series is also a lookup table. Its index holds the keys and its values hold the results. A dict passed to map is converted to a Series internally, so the two behave the same way.
import pandas as pd
codes = pd.Series(["A1", "B2", "A1", "C3"])
prices = pd.Series({"A1": 9.5, "B2": 4.0, "C3": 12.0})
print(codes.map(prices))0 9.5
1 4.0
2 9.5
3 12.0
dtype: float64Two details are easy to get wrong.
- The lookup uses the index of the mapper, not its values. If your lookup data sits in a column, move the key column into the index first.
- The result takes the index of the calling Series (
codes). The index ofpricesonly supplies the keys.
A common case is a lookup table stored as a DataFrame:
import pandas as pd
orders = pd.DataFrame({"code": ["A1", "B2", "A1", "C3"], "qty": [1, 2, 3, 1]})
lookup = pd.DataFrame({"code": ["A1", "B2", "C3"], "price": [9.5, 4.0, 12.0]})
orders["price"] = orders["code"].map(lookup.set_index("code")["price"])
orders["total"] = orders["price"] * orders["qty"]
print(orders) code qty price total
0 A1 1 9.5 9.5
1 B2 2 4.0 8.0
2 A1 3 9.5 28.5
3 C3 1 12.0 12.0set_index("code")["price"] produces a Series keyed by code, which is what map needs.
The lookup index must be unique
If the mapper Series has duplicate index labels, pandas cannot decide which value to return, and it raises an error.
import pandas as pd
table = pd.Series([1, 2], index=["a", "a"])
try:
pd.Series(["a"]).map(table)
except Exception as err:
print(type(err).__name__)InvalidIndexErrorRemove the duplicates before mapping, and decide on purpose which row to keep:
import pandas as pd
table = pd.Series([1, 2], index=["a", "a"])
unique_table = table[~table.index.duplicated(keep="first")]
print(pd.Series(["a"]).map(unique_table))0 1
dtype: int64A dict cannot have duplicate keys, so this problem appears only when the lookup comes from data, such as a column loaded from a file.
Choosing between a dict and a function
Both forms are valid, and they suit different jobs.
| Situation | Better choice |
|---|---|
| A finite list of known values, such as codes or labels | dict or Series |
| A rule that works for any value, such as upper-casing or arithmetic | function |
| Lookup data already stored in a column or file | Series (via `set_index`) |
| Unmapped values must stay unchanged | `replace`, or `map(...).fillna(s)` |
| The result depends on several columns | `DataFrame.apply` or a vectorized expression |
A dict or Series lookup is also usually faster than a function. pandas resolves the whole column through its index machinery instead of calling Python code once for every row. On a large column with a small set of distinct values, the difference is large. For a lookup, prefer the table form over map(lambda x: d.get(x)).
Common errors
- Unexpected
NaNvalues. The dict is missing keys, or the keys differ in type or spelling. The integer1and the string"1"are different keys. Whitespace and capitalization matter too. Clean the column first, for example withs.str.strip().str.lower(), then map. - Wrong dtype after mapping.
NaNturns integers into floats. If the mapping is complete, the dtype is the common type of your dict values. If it is not, you will seefloat64orobject. - Mapping with the values instead of the index. Passing
lookup["price"]without setting the key column as the index makes pandas look up your keys among the row numbers0, 1, 2, ..., which gives mostlyNaN. - Expecting in-place changes.
mapreturns a new Series. Assign it back, or the original stays as it was. - Using
mapfor multi-column lookups. A key made of two columns does not fitmap. UseDataFrame.mergefor that case.
The last point is a boundary of this method. map joins on one key, and it keeps your row count and order fixed. That is what you want for adding a single column. A merge is more general, but you must watch for row duplication when the right-hand table has repeated keys.
Exercise
A Series s = pd.Series(["red", "green", "blue"]) is mapped with s.map({"red": 1, "green": 2}). What are the resulting values and dtype, and how would you keep "blue" unchanged instead?
Show answer
The result is 1.0, 2.0, NaN with dtype float64, because "blue" has no key and the NaN forces floats. To keep "blue", use s.replace({"red": 1, "green": 2}). That gives 1, 2, "blue" with dtype object. Using s.map({"red": 1, "green": 2}).fillna(s) has the same effect.
Exercise
You have sales = pd.DataFrame({"sku": ["p", "q", "p"]}) and info = pd.DataFrame({"sku": ["p", "q"], "name": ["Pen", "Quill"]}). Write one line that adds a name column to sales using map.
Show answer
sales["name"] = sales["sku"].map(info.set_index("sku")["name"]). The set_index("sku")["name"] part builds a Series keyed by SKU. map uses its index as the lookup keys and returns the names in the order of sales.