The pandas.Series.replace() method in Pandas
The pandas.Series.replace() function in Python is used to replace values in a pandas.Series object.
Syntax a) Series.replace(value to replace1, Replacement value1)
b) Series.replace({value to replace1: Replacement value1, value to replace 2: Replacement value 2})
Example: Load the csv file data.csv into a dataframe.
Python
# Load Data into Pandas DataFrame # df = pd.read_csv("file_path") df = pd.read_csv("data.csv") df
The output of the above code is shown below:
Let’s replace the Gender column values Male and Female to 0 and 1 respectively, by using the replace method in Pandas.
Python
df["New Gender"]=df['Gender'].replace({'Male': 0, 'Female': 1}) df
The output of the above code is shown below: