Sub topic 9
Recoding values with map and replace
This chapter assumes you can build a DataFrame, select a column by name, and assign a new column. Recoding means swapping the values in a column for other values, such as turning codes into labels. Both map and replace do this. They differ in what they do with values you don't mention.
Recoding with map
Series.map accepts a dictionary, a Series, or a function. With a dictionary, each value is looked up as a key. A value with no matching key becomes NaN.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
})
codes = df["item"].map({"pen": "P", "book": "B"})
print(codes)The output shows P, B, and NaN. The item lamp is missing from the dictionary, so it has no code. This is useful when you want unmapped values to stand out. It is a problem when you meant to keep them.
To keep the original value as a fallback, combine map with fillna:
df["code"] = df["item"].map({"pen": "P", "book": "B"}).fillna(df["item"])
print(df)Recoding with replace
Series.replace changes only the values you list. Everything else stays as it was.
df["item_short"] = df["item"].replace({"pen": "P", "book": "B"})
print(df)Here lamp remains lamp. replace can also take lists, and it can substitute one value everywhere in a whole DataFrame.
status = pd.Series(["Y", "N", "Y", "?"])
print(status.replace(["Y", "N"], [True, False]))Choosing between them
| Question | `map` | `replace` |
|---|---|---|
| Value not in the dictionary | Becomes `NaN` | Left unchanged |
| Accepts a function | Yes | No |
| Accepts a Series as lookup | Yes | No |
| Typical use | Full lookup table | Fixing a few values |
Use map when your dictionary is meant to cover every valid value. Unexpected values then show up as NaN, and you can find them with isna(). Use replace when you want to correct a few known values and leave the rest alone.
unmapped = df.loc[df["item"].map({"pen": "P", "book": "B"}).isna(), "item"]
print(unmapped.tolist())Common errors
- Forgetting that
mapproducesNaNfor unlisted values, then finding missing data later. - Expecting
replaceto flag unexpected values. It stays silent about them. - Using
mapwith a dictionary on a column of numbers, where the keys must match the numeric type exactly. A key of"1"will not match the integer1. - Writing
df["col"].replace(...)without assigning the result. Neither method changes the original in place unless you assign the result back.
Exercise
A column grade holds "A", "B", and "C". You run df["grade"].map({"A": 4, "B": 3}). What does the row with "C" contain, and how would you keep the original "C" instead?
Show answer
The row contains NaN because "C" is not a key in the dictionary. Use df["grade"].replace({"A": 4, "B": 3}) to leave "C" unchanged, or call .fillna(df["grade"]) after map.