pandas replace
Series.replace(old, new) swaps whole values that match exactly, and a dict replaces several at once: df["col"].replace({"Y": "yes", "N": "no"}). Values that are not in the dict stay as they are. To change part of a text value use str.replace or regex=True.
Syntax
Series.replace(to_replace, value, regex=False) | df.replace({column: {old: new}})| Part | What it is |
|---|---|
to_replace | Value, list, dict of old: new, or a regex pattern to look for |
value | Replacement, when to_replace is not a dict |
regex | True treats to_replace as a regular expression |
Examples
import pandas as pd
import numpy as np
df = pd.DataFrame({"status": ["Y", "N", "n/a", "Y"],
"score": [10, -1, 7, -1]})
df["status"].replace({"Y": "yes", "N": "no"})Result:
0 yes
1 no
2 n/a
3 yes
Name: status, dtype: objectn/a is not in the dict, so it is left alone.
df.replace({"status": {"n/a": np.nan}, "score": {-1: np.nan}})Result:
status score
0 Y 10.0
1 N NaN
2 NaN 7.0
3 Y NaNA nested dict replaces different placeholders in different columns. score becomes float because NaN is a float.
df["status"].replace(r"^n.*", "missing", regex=True)Result:
0 Y
1 N
2 missing
3 Y
Name: status, dtype: objectWith regex=True the pattern is matched against text values; the capital N does not match a lowercase n.
df["status"].str.replace("/", "")Result:
0 Y
1 N
2 na
3 Y
Name: status, dtype: objectstr.replace changes part of each string, which plain replace does not.
Try it yourself
Rename the columns Qty to qty, Unit Price to unit_price and Region to region. Then replace the text "N/A" in the region column with "Unknown". Return the table.
raw: 4 rows, first 4 shown
| Qty | Unit Price | Region |
|---|---|---|
| 3 | 9.99 | "East" |
| 1 | 24.5 | "N/A" |
| 7 | 3.25 | "West" |
| 2 | 12 | "N/A" |
Free, no account needed. Real pandas runs in your browser; the first run takes a few seconds to load Python.
Common mistakes
- Nothing is replaced: replace matches the whole value. replace("n", "x") does not touch "n/a"; use str.replace or regex=True for parts of a string.
- Forgetting to assign: replace returns a new object. Write df["col"] = df["col"].replace(...).
- Using replace to recode every value: values missing from the dict are kept. If unlisted values should become NaN, use map instead.
More practice: replace
These drills check your answer on live data, free, no account needed.
- Recode values with mapAdd a column `score` to `tickets` that turns the priority into a number: low is 1, medium is 2 and high is 3. A priority that is not one of those three gets NaN. Return the whole DataFrame with the new column.
Questions
How do I replace values based on a condition?
Use loc: df.loc[df["score"] < 0, "score"] = 0, or np.where(df["score"] < 0, 0, df["score"]).
How do I replace NaN values?
fillna is the tool for that: df["col"].fillna(0).
What is the difference between replace and map?
replace keeps values it has no rule for; map turns them into NaN. Use map when the dict is meant to cover every value.
Related
- mapHow Series.map works in pandas to recode a column with a dict or lookup Series, apply a function per value, what unmatched values become, and map vs replace.
- fillnaHow to fill NaN values in pandas with fillna: a constant, a different value per column, the column mean or median, forward and backward fill, and by group.
- str.containsHow to use str.contains in pandas to find rows containing text: case-insensitive matching, several keywords with regex, literal characters, and the NaN error.
- where, mask and np.whereHow to create a conditional column in pandas: np.where for if-else, np.select for several conditions, Series.where to keep values that pass a test, and mask.
- astypeHow to change a column type in pandas with astype and pd.to_numeric: text to numbers, float to int, strings, categories, nullable Int64, bad values and NaN.
Interview and translation guides
- Timed mock interview
- pandas interview questions
- The pandas interview round
- SQL to pandas
- XLOOKUP in pandas
- pandas for Excel users
- groupby exercises