← Back to Pandas Course | Chapter 5: Data Cleaning | Lesson 6 of 7

Replacing values

replace swaps specific values for others across a whole Series or DataFrame.

In this page:

  1. Replacing values
Syntax
python
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

python
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
  1. Not converting placeholders to NaN
  2. Replacing in a copy and losing the change
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.