Pandas Dataframe: Replace Examples

Pandas Dataframe: Replace Examples

Last updated:
Table of Contents

View examples on this notebook

Replace value anywhere

use inplace=True to mutate the dataframe itself

This is the simplest possible example.

Usedf.replace([v1,v2], v3) to replace all occurrences of v1 and v2 with v3

import pandas as pd

df = pd.DataFrame({
    'name':['john','mary','paul'],
    'age':[30,25,40],
    'city':['new york','los angeles','london']
})

df.replace([25],40)

Original dataframe Original dataframe
Replaced 25 with 40. Simple. Replaced 25 with 40. Simple.

Replace with dict

Use df.replace{from1:to1, from2:to2, ...}

import pandas as pd

df = pd.DataFrame({
    'name':['john','mary','paul'],
    'age':[30,25,40],
    'city':['new york','los angeles','london']
})

df.replace({
    25:26,
    'john':'johnny'
})

Original dataframe Original dataframe
dict-replacement Use a dict to specify multiple replacements

Replace with regex

Use df.replace(pattern, replacement, regex=True)

import pandas as pd

df = pd.DataFrame({
    'name':['john','mary','paul'],
    'age':[30,25,40],
    'city':['new york','los angeles','london']
})

df.replace('jo.+','FOO',regex=True)

Original dataframe Original dataframe
regex-replacement Use regex to replace in string columns

Replace in single column

Use df.replace({colname:{from:to}})

df = pd.DataFrame({
    'name':['john','mary','paul'],
    'num_children':[0,4,5],
    'num_pets':[0,1,2]
})

# replace 0 with 1 in column "num_pets" only!
df.replace({'num_pets':{0:1}})

original-dataframe Original Dataframe
only-one-column-was-replaced You can use a dict within a dict to specify
replacements in a specific column only.


Reference