xxxxxxxxxx
df['column name'] = df['column name'].replace(['old value'], 'new value')
xxxxxxxxxx
# 1. Replace a single value with a new value for an individual DataFrame column:
df['column name'] = df['column name'].replace(['old value'],'new value')
# 2. Replace multiple values with a new value for an individual DataFrame column:
df['column name'] = df['column name'].replace(['1st old value','2nd old value', ],'new value')
# 3. Replace multiple values with multiple new values for an individual DataFrame column:
df['column name'] = df['column name'].replace(['1st old value','2nd old value', ],['1st new value','2nd new value', ])
# 4. Replace a single value with a new value for an entire DataFrame:
df = df.replace(['old value'],'new value')
xxxxxxxxxx
# Replace missing values
df["col"].replace(np.nan, new_val)
# Replace other values
df["col"].str.replace('old','new')
# Replace using masking
df.loc[df['col']=='old', 'col'] = 'new'
# Replace all specified value in the dataframe
df_replaced = df.replace(1, 0)
xxxxxxxxxx
df.loc[df['column_name'] == value_you_want_replaced, 'column_name'] = your_value
xxxxxxxxxx
# replace() syntax
DataFrame.replace(to_replace="<the_value_you_want_to_replace>", value="<new_value_for_input>", inplace=False, limit=None, regex=False, method='pad')
xxxxxxxxxx
# Importing the libraries
import pandas as pd
import numpy as np
# data
Student = {
'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'],
'gender': ['male', 'male', 'male', 'female', 'female', 'male'],
'math score': [50, 100, 70, 80, 75, 40],
'test preparation': ['none', 'completed', 'none', 'completed',
'completed', 'none'],
}
# creating a Dataframe object
df = pd.DataFrame(Student)
# Applying the condition
df.loc[df["gender"] == "male", "gender"] = 1