How to replace values in a column of a Pandas DataFrame?

Published on Aug. 22, 2023, 12:19 p.m.

To replace values in a column of a Pandas DataFrame, you can use the replace() method. Here is an example:

import pandas as pd

# Create a sample DataFrame with a column of names
data = {'name': ['John', 'Jane', 'Bob']}
df = pd.DataFrame(data)

# Replace 'John' with 'Sam' in the 'name' column
df['name'] = df['name'].replace('John', 'Sam')

# Print the updated DataFrame
print(df)

This code will output the following DataFrame with the replaced value:

name
0  Sam
1  Jane
2  Bob

You can also replace multiple values at once by passing a dictionary to the replace() method. For example:

# Replace 'John' with 'Sam' and 'Jane' with 'Mary' in the 'name' column
df['name'] = df['name'].replace({'John': 'Sam', 'Jane': 'Mary'})

# Print the updated DataFrame
print(df)

This will output the following DataFrame with both values replaced:

name
0   Sam
1  Mary
2   Bob

Note that the replace() method returns a new DataFrame with the replaced values, so you need to assign the result back to the original DataFrame or a new variable if you want to keep the changes.

Tags: