Sub topic 3
Mapping values with a dict or Series
This chapter assumes you can write a basic Python function or lambda, build a pandas Series, and assign a new column to a DataFrame. The previous chapter passed a function to Series.map. Here you pass a lookup table instead.
How map treats a dict
When the argument to map is a dict, pandas does not call anything. It takes each element of the Series, uses it as a key, and returns the matching value. This suits recoding tasks such as turning codes into labels.
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.map({"a": "x", "b": "y"}))The output is:
0 x
1 y
2 NaN
dtype: objectThe value "c" has no key in the dict, so its result is NaN. map never raises an error for a missing key.
Using a Series as the lookup
You can also pass a Series. Its index acts as the keys and its values are the results. This is useful when the lookup table already lives in pandas, for example after loading it from a file.
import pandas as pd
codes = pd.Series(["US", "DE", "US", "FR"])
names = pd.Series({"US": "United States", "DE": "Germany"})
result = codes.map(names)
print(result)The output is:
0 United States
1 Germany
2 United States
3 NaN
dtype: objectThe result keeps the index of codes, not the index of names. The lookup Series only supplies the key-to-value pairs. Because it matches on keys, the order of the rows in names does not matter.
Handling keys that are not found
Unmatched elements become NaN, which often surprises people when the column was integers or strings. Chain fillna to supply a default:
import pandas as pd
codes = pd.Series(["US", "DE", "US", "FR"])
names = {"US": "United States", "DE": "Germany"}
print(codes.map(names).fillna("Unknown"))If you want unmatched values to stay as they were, use replace instead of map. It leaves values that are not in the dict untouched. A dict subclass that defines __missing__, such as defaultdict, also gives you a default in place of NaN.
Common errors
- Unexpected NaN. Keys must match exactly.
"us"does not match"US", and the integer1does not match the string"1". Check the dtype of the Series and of the dict keys. - Changed dtype. An integer column that receives even one
NaNbecomesfloat64. A column of recoded strings has dtypeobject. - Duplicate index in the lookup Series. A lookup Series must have unique index labels. Otherwise pandas raises a
ValueError, because one key would have several possible results.
import pandas as pd
keys = pd.Series(["a", "b"])
lookup = pd.Series([1, 2, 3], index=["a", "b", "a"])
try:
keys.map(lookup)
except ValueError as err:
print("ValueError:", err)To fix this, remove duplicates first, for example with lookup[~lookup.index.duplicated()].
Choosing between a dict and a Series
| Lookup source | Best when |
|---|---|
| dict | The table is small and written in your code |
| Series | The table already exists as pandas data, such as a column pair from a file |
In both cases the work is done by a hash lookup, so mapping is typically faster than calling a Python function for each element.
Exercise
A Series grades = pd.Series(["A", "B", "D", "A"]) is mapped with {"A": 4, "B": 3, "C": 2}. What is the result, and what is its dtype?
Show answer
The result is [4.0, 3.0, NaN, 4.0]. The value "D" has no key, so it becomes NaN. Because NaN is a float, the whole Series has dtype float64, so the integers appear as 4.0 and 3.0.