Bird
Raised Fist0
PandasHow-ToBeginner · 3 min read

How to Replace Values in pandas DataFrames and Series

In pandas, you can replace values using the replace() method on a DataFrame or Series. This method lets you specify the values to find and what to replace them with, either as single values, lists, or dictionaries.
📐

Syntax

The basic syntax of replace() is:

  • df.replace(to_replace, value=None, inplace=False, regex=False)

Where:

  • to_replace: value(s) to find (single value, list, or dict)
  • value: value(s) to replace with (single value, list, or dict), optional
  • inplace: if True, modifies the original DataFrame/Series
  • regex: if True, treats to_replace as regex pattern
python
df.replace(to_replace, value=None, inplace=False, regex=False)
💻

Example

This example shows how to replace specific values in a pandas DataFrame using replace(). It replaces 1 with 100 and 'cat' with 'dog'.

python
import pandas as pd

data = {'A': [1, 2, 3, 1], 'B': ['cat', 'dog', 'cat', 'mouse']}
df = pd.DataFrame(data)

# Replace 1 with 100 and 'cat' with 'dog'
df_replaced = df.replace({1: 100, 'cat': 'dog'})

print(df_replaced)
Output
A B 0 100 dog 1 2 dog 2 3 dog 3 100 mouse
⚠️

Common Pitfalls

Common mistakes when using replace() include:

  • Not using inplace=True if you want to modify the original DataFrame.
  • Confusing replace() with map() or apply() which serve different purposes.
  • Passing mismatched types in to_replace and value causing unexpected results.
  • Forgetting that replace() works element-wise and does not filter rows.

Example of wrong and right usage:

python
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3]})

# Wrong: expecting original df to change without inplace
_df_wrong = df.replace(1, 100)
print(df)  # Original unchanged

# Right: use inplace=True to modify original
df.replace(1, 100, inplace=True)
print(df)  # Original changed
Output
A 0 1 1 2 2 3 A 0 100 1 2 2 3
📊

Quick Reference

ParameterDescription
to_replaceValue(s) to find and replace (single, list, or dict)
valueValue(s) to replace with (single, list, or dict)
inplaceIf True, modifies original DataFrame/Series (default False)
regexIf True, treats to_replace as regex pattern (default False)
✅

Key Takeaways

Use pandas' replace() method to swap values easily in DataFrames or Series.
Pass dictionaries to replace() for multiple replacements at once.
Set inplace=True to change the original data directly.
Be careful with data types and use regex=True for pattern matching.
replace() works element-wise and does not filter rows.