Normalize labels
Standardizing categorical data before analysis.
Pandas · Module
Replaces matching values in a DataFrame with specified alternatives. It supports scalar, list, dictionary, and regular-expression-based replacements, and returns a new frame unless inplace=True.
DataFrame.replace searches the frame for values matching to_replace and substitutes them with value. It returns a changed copy by default, while inplace=True applies the operation to the existing frame; dictionaries can express different mappings or column-specific replacements.
DataFrame.replace(*to_replace=None*, *value=<no_default>*, ***, *inplace=False*, *regex=False*)| Name | Type | Description |
|---|---|---|
to_replace | str, regex, list, dict, Series, int, float, or None | Values to search for and replace; accepts strings, regular expressions, lists, dictionaries, Series, numbers, or None. |
value | scalar, dict, list, str, regex, default None | Replacement value for matches; it may be a scalar, dictionary, list, string, regular expression, or None. |
inplace | bool, default False | Whether to modify the existing DataFrame instead of returning a new result. |
regex | bool or same types as to_replace, default False | Whether to interpret to_replace and/or value as regular expressions. |
DataFrame or None if inplace=True
import pandas as pd
frame = pd.DataFrame({"status": ["new", "pending", "new"], "score": [1, 2, 1]})
cleaned = frame.replace({"new": "open", "pending": "waiting", 1: 10})
print(cleaned)Creates a new DataFrame with selected scalar values replaced across the data.
Standardizing categorical data before analysis.
Converting sentinel numeric values into meaningful values.
Applying text-pattern transformations across columns.
It matches values described by to_replace and substitutes the corresponding value. Unlike .loc or .iloc, it selects values by their contents rather than requiring an explicit location.
Follow-up: How would you perform pattern-based replacement? Set regex=True, or provide regular expressions in the supported regex forms.
A dictionary can map several existing values to their replacements. For a DataFrame, a dictionary value can also specify replacements by column, leaving columns absent from that mapping unchanged.
Follow-up: What happens when regex=True with two lists? Strings in both lists are interpreted as regular expressions rather than literal matches.
The default is inplace=False, so the operation returns a replaced DataFrame and does not modify the original. Setting inplace=True performs the operation on the existing object.
Follow-up: Which option controls pattern interpretation? The regex parameter determines whether to interpret to_replace and/or value as regular expressions.
Series.replaceDataFrame.maskDataFrame.whereDataFrame.fillna