replace() can substitute a single value everywhere it appears, replace multiple different values with the same new value using a list, or map several distinct old values to different new values at once using a dict. Passing regex=True lets to_replace be a regular expression pattern instead of an exact value, matching and replacing based on a pattern rather than requiring an identical string.
1Understanding df.replace()
replace() can substitute a single value everywhere it appears, replace multiple different values with the same new value using a list, or map several distinct old values to different new values at once using a dict. Passing regex=True lets to_replace be a regular expression pattern instead of an exact value, matching and replacing based on a pattern rather than requiring an identical string.
Use a dict with replace(), mapping each old value to its corresponding new value, to remap several distinct values to different new values in a single call, rather than chaining multiple separate replace() calls.
import pandas as pd
df = pd.DataFrame({"status": ["Y", "N", "Y", "N"]})
print(df.replace({"Y": "Yes", "N": "No"}))2Practical Example
Here is a real-world application of df.replace() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"phone": ["555-1234", "555-5678"]})
print(df.replace(r"555-", "", regex=True))3Best Practices
Follow these guidelines when working with df.replace():
1. Use a dict argument to replace() when different old values need to map to different new values, instead of chaining multiple replace() calls
2. Pass regex=True when the values to replace are better described by a pattern than an exact literal match
3. Prefer replace() over manual boolean-indexing assignment for straightforward value substitution, since it's more concise and handles multiple mappings at once
Tip: Use a dict with replace(), mapping each old value to its corresponding new value, to remap several distinct values to different new values in a single call, rather than chaining multiple separate replace() calls.
import pandas as pd
df = pd.DataFrame({"status": ["Y", "N", "Y", "N"]})
print(df.replace({"Y": "Yes", "N": "No"}))