Pandas – df.replace() – How to replace values in pandas

Spread the love

In this post, you will learn –

1 . How to replace a value with a single value in a column

2 . How to replace multiple values with a single value in a column

3 . How to replace multiple values with multiple values in a column

4 . How to replace a value with another value in the entire dataframe.

1 . How to replace a value with a single value in a column

Read the dataset to work with.

import pandas as pd
import numpy as np

df = pd.read_csv(
    "https://raw.githubusercontent.com/bprasad26/lwd/master/data/titanic.csv"
)
df.head()

Let’s say that you want to replace all the NaN (Not a number) values in the Cabin column with 0. To do that we can use

df["Cabin"] = df["Cabin"].replace(np.nan, 0)

2 . How to replace multiple value with a single value in a column

Let’s say that you want to replace both the C85 and C123 in the cabin column with just C

df["Cabin"] = df["Cabin"].replace(["C85", "C123"], "C")

3 . How to replace multiple values with multiple values in a column

Suppose you want to change male with m and female with f

df["Sex"] = df["Sex"].replace({"male": "m", "female": "f"})

4 . How to replace a value with another value in the entire dataframe

Let’s say that you want to replace all 1 in dataframe with -999. To do that you will write

df = df.replace(1, -999)

Rating: 1 out of 5.

Leave a Reply