Pandas Dataframe: Replace Examples

Last updated:
Table of Contents

View examples on this notebook

Simplest possible example: replace one value with another

use inplace=True to mutate the dataframe itself

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

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

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

df = pd.DataFrame({
    'name':['john','mary','paul'],
    'num_children':[0,4,5],
    'num_pets':[0,1,2]
})
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

Dialogue & Discussion