Replacing values
replace swaps specific values for others across a whole Series or DataFrame.
In this page:
Syntax
df["column"].replace(old_value, new_value)
df.replace({"old1": "new1", "old2": "new2"})
Replacing values
replace accepts a single value, a list, or a dict mapping old values to new ones. It can also use regex. It is ideal for recoding categories or turning placeholders such as -999 into NaN.
Note:
Replace sentinel values like -999 or "N/A" with np.nan so Pandas treats them as missing.
Example: Replacing values
import pandas as pd
import numpy as np
df = pd.DataFrame({"grade": ["A", "B", "N/A"], "score": [90, -999, 70]})
df = df.replace({"N/A": np.nan, -999: np.nan})
print(df)
print(df["grade"].replace({"A": "Excellent", "B": "Good"}))
# Output:
# grade score
# 0 A 90.0
# 1 B NaN
# 2 NaN 70.0
# 0 Excellent
# 1 Good
# 2 NaN
# Name: grade, dtype: object
Related Topics
Common Mistakes
- Not converting placeholders to NaN
- Replacing in a copy and losing the change
- Using replace when map is more appropriate
Chapter Summary
- replace maps old to new values
- Accepts dicts and lists
- Great for sentinel values
- Supports regex
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: