Sub topic 9
Recoding values with map and replace
Recoding means swapping the values in a column for other values: codes for labels, abbreviations for full names, typos for the correct spelling. In pandas, Series.map and Series.replace both do this, but they treat values that you don't list in different ways. Choosing the wrong one is a common source of silent data loss.
This chapter assumes you can build a DataFrame, select a column by name, and assign a new column with df["name"] = .... You should also know that a column is a Series and that missing values appear as NaN.
The core difference
The two methods differ in what happens to values that are not in your mapping.
| Behavior | `Series.map(dict)` | `Series.replace(dict)` |
|---|---|---|
| Value found in dictionary | Replaced | Replaced |
| Value not in dictionary | Becomes `NaN` | Left unchanged |
| Typical use | Full recode of a column | Fixing a few values |
| Accepts function or Series | Yes | No (uses regex, lists, dicts) |
Use map when your dictionary is meant to cover every value, so that anything unexpected shows up as NaN. Use replace when you only want to fix some values and keep the rest.
Recoding with map
Pass a dictionary to map. Each value in the column is looked up as a key.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
codes = df["item"].map({"pen": "P", "book": "B"})
print(codes)The output is:
0 P
1 B
2 NaN
Name: item, dtype: object"lamp" is not a key, so its result is NaN. This is useful as a check: if you expected the dictionary to be complete, count the NaN values afterwards.
unmapped = codes.isna() & df["item"].notna()
print(df.loc[unmapped, "item"].unique())The df["item"].notna() part matters. A value that was already missing would also produce NaN, and you only want to catch values that were present but had no mapping.
Keeping unmapped values with map
If you want map to fall back to the original value, chain fillna with the original column:
mapping = {"pen": "P", "book": "B"}
df["code"] = df["item"].map(mapping).fillna(df["item"])
print(df)fillna accepts a Series and aligns it by index, so each NaN is filled with the original value from the same row. This works only when the original column has no NaN that you want to preserve as missing. Here the result is P, B, lamp.
Other arguments to map
map accepts three kinds of argument:
- A dictionary, which is looked up by key.
- A Series, whose index acts as the keys.
- A function, which is called once per value.
lengths = df["item"].map(len)
upper = df["item"].map(str.upper)A function passed to map runs in a Python loop, so it is slower than a vectorized operation. Prefer .str methods when one exists, such as df["item"].str.upper().
If the column holds missing values and you pass a function, the function is called on the NaN too, which can raise an error. Pass na_action="ignore" to skip them:
names = pd.Series(["ann", None, "bob"])
print(names.map(str.title, na_action="ignore"))Recoding with replace
replace leaves anything it doesn't recognize alone.
status = pd.Series(["Y", "N", "Y", "maybe"])
print(status.replace({"Y": "yes", "N": "no"}))The result is yes, no, yes, maybe. The value "maybe" survives. This makes replace the better choice for cleaning, where you fix known problems without discarding the rest.
Forms of replace
replace takes several argument shapes:
s = pd.Series([1, 2, -999, 4, -999])
s.replace(-999, float("nan")) # one value to one value
s.replace([1, 2], [10, 20]) # lists, matched by position
s.replace({-999: float("nan"), 4: 40}) # dictionaryThe first form is a common way to turn a sentinel value (a number that stands for "unknown", such as -999) into a real NaN, so that later calculations skip it.
Replacing across a whole DataFrame
Called on a DataFrame, replace applies to every column. To limit it to specific columns, use a nested dictionary where the outer key is the column name:
data = pd.DataFrame({
"grade": ["A", "B", "N/A"],
"note": ["N/A", "ok", "ok"],
})
print(data.replace({"grade": {"N/A": "none"}}))Only the grade column is changed. The "N/A" in note stays.
Regular expressions
Set regex=True to match patterns instead of whole values. Without it, replace only matches a value that equals the key exactly.
phones = pd.Series(["555-1234", "555 9876"])
print(phones.replace(r"[\s-]", "", regex=True))This removes both hyphens and spaces. For text cleaning inside longer strings, .str.replace is often clearer, and it is the one to use when you want substring replacement on a text column.
Matching exactly: keys must equal the values
Both methods compare using equality, so small differences stop a match. "Pen", "pen " and "pen" are three different keys. Clean the text first:
raw = pd.Series(["Pen", "pen ", "BOOK"])
clean = raw.str.strip().str.lower()
print(clean.map({"pen": "P", "book": "B"}))Types matter as well. The integer 1 and the string "1" do not match each other. If map returns all NaN on a column that looks right, check df["col"].dtype and df["col"].unique().
Missing values as keys
A NaN in the column is looked up like any other value. In map, you can include float("nan") as a key, though fillna is usually clearer. In replace, NaN can be a key too:
s = pd.Series(["a", None, "b"])
print(s.replace({None: "unknown"}))For plain missing-value filling, prefer fillna. Use replace when missing values are only one of several things you are recoding.
Categorical columns
On a category dtype column, map returns a categorical result when the mapping is one-to-one, and it ignores the na_action default differently from object columns. If you run into surprises, convert with astype(str) or astype(object) before mapping, or use rename_categories to relabel the categories themselves.
Choosing between them
- Is the dictionary meant to cover every value, with surprises treated as errors? Use
map, then check forNaN. - Are you fixing a handful of known bad values? Use
replace. - Do you need a computed rule rather than a lookup? Use a function with
map, or a vectorized method ornp.selectwhen possible. - Do you need pattern matching? Use
replace(..., regex=True)or.str.replace.
Common errors
- Unexpected
NaNafter map. A key is missing or does not match because of case, whitespace, or type. Inspectunique()on the source column. - Nothing changes after replace. Both methods return a new Series. You must assign the result, for example
df["col"] = df["col"].replace(...). Calling it without assignment does nothing todf. - Regex surprises. With
regex=True, characters such as.and(have special meaning. Escape them withre.escapewhen you mean them literally. - Mixed dtypes. Mapping integers to strings changes the column dtype to
object. Check dtypes afterwards if later code depends on them.
Exercise
A column size contains "S", "M", "L", and a typo "XL " (with a trailing space). You run df["size"].map({"S": 1, "M": 2, "L": 3, "XL": 4}). Which rows become NaN, and how do you fix the code so that "XL " becomes 4?
Show answer
The "XL " row becomes NaN, because the key "XL" does not equal "XL " with its trailing space. Strip whitespace before mapping: df["size"].str.strip().map({"S": 1, "M": 2, "L": 3, "XL": 4}).
Exercise
A Series s = pd.Series([5, -1, 7, -1]) uses -1 for "unknown". Write one line that makes the unknowns real missing values, and say whether s itself changes.
Show answer
s.replace(-1, float("nan")). The call returns a new Series, so s is unchanged unless you assign the result back, as in s = s.replace(-1, float("nan")).