We use replace() to change specific values in data. It helps fix mistakes or update data easily.
replace() for value substitution in Pandas
import pandas as pd # Create a DataFrame or Series # Use replace() to swap old values with new ones # df.replace(to_replace, value, inplace=False) # to_replace: value or list/dict of values to find # value: value or list/dict of values to replace with # inplace: if True, changes original data; else returns new data
You can replace single values or multiple values at once.
Use inplace=True to change the original data directly.
import pandas as pd # Example 1: Replace single value in a Series fruits = pd.Series(['apple', 'banana', 'apple', 'orange']) fruits_replaced = fruits.replace('apple', 'pear') print(fruits_replaced)
import pandas as pd # Example 2: Replace multiple values in a DataFrame data = pd.DataFrame({ 'A': ['cat', 'dog', 'cat'], 'B': ['red', 'blue', 'red'] }) data_replaced = data.replace({'cat': 'lion', 'red': 'green'}) print(data_replaced)
import pandas as pd # Example 3: Replace value in empty Series empty_series = pd.Series([], dtype=object) empty_replaced = empty_series.replace('old', 'new') print(empty_replaced)
import pandas as pd # Example 4: Replace value at the start and end series = pd.Series(['start', 'middle', 'end']) series_replaced = series.replace({'start': 'begin', 'end': 'finish'}) print(series_replaced)
This program shows how to replace all 'B' grades with 'B+' in the 'Grade' column of a DataFrame.
import pandas as pd # Create a DataFrame with some values student_scores = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Grade': ['A', 'B', 'C', 'B'] }) print('Original DataFrame:') print(student_scores) # Replace grade 'B' with 'B+' updated_scores = student_scores.replace({'Grade': {'B': 'B+'}}) print('\nDataFrame after replace():') print(updated_scores)
Time complexity: Usually O(n), where n is number of elements to check.
Space complexity: O(n) if inplace=False because it creates a new object.
Common mistake: forgetting to assign the result back or use inplace=True, so original data stays unchanged.
Use replace() when you want to change specific values without affecting others. For complex changes, consider mapping or conditional logic.
replace() helps swap specific values in pandas data.
You can replace one or many values at once using dicts or lists.
Remember to assign the result or use inplace=True to keep changes.