Examples
Scalar to_replace and value

In [1]:
import numpy as np
import pandas as pd
In [2]:
s = pd.Series([0, 2, 3, 4, 5])
s.replace(0, 6)
Out[2]:
0    6
1    2
2    3
3    4
4    5
dtype: int64
In [3]:
df = pd.DataFrame({'P': [0, 2, 3, 4, 5],
                   'Q': [6, 7, 8, 9, 10],
                   'R': ['p', 'q', 'r', 's', 't']})
df.replace(0, 6)
Out[3]:
P Q R
0 6 6 p
1 2 7 q
2 3 8 r
3 4 9 s
4 5 10 t

List-like to_replace

In [4]:
df.replace([0, 2, 3, 4], 5)
Out[4]:
P Q R
0 5 6 p
1 5 7 q
2 5 8 r
3 5 9 s
4 5 10 t
In [5]:
df.replace([0, 2, 3, 4], [5, 4, 3, 2])
Out[5]:
P Q R
0 5 6 p
1 4 7 q
2 3 8 r
3 2 9 s
4 5 10 t
In [6]:
s.replace([2, 3], method='bfill')
Out[6]:
0    0
1    4
2    4
3    4
4    5
dtype: int64

dict-like to_replace

In [7]:
df.replace({0: 20, 2: 200})
Out[7]:
P Q R
0 20 6 p
1 200 7 q
2 3 8 r
3 4 9 s
4 5 10 t
In [8]:
df.replace({'P': 0, 'Q': 6}, 100)
Out[8]:
P Q R
0 100 100 p
1 2 7 q
2 3 8 r
3 4 9 s
4 5 10 t
In [9]:
df.replace({'P': {0: 200, 4: 400}})
Out[9]:
P Q R
0 200 6 p
1 2 7 q
2 3 8 r
3 400 9 s
4 5 10 t

Regular expression to_replace

In [10]:
df = pd.DataFrame({'P': ['bar', 'ffa', 'bfg'],
                   'Q': ['mno', 'bat', 'xyz']})
df.replace(to_replace=r'^ba.$', value='new', regex=True)
Out[10]:
P Q
0 new mno
1 ffa new
2 bfg xyz
In [11]:
df.replace({'P': r'^ba.$'}, {'P': 'new'}, regex=True)
Out[11]:
P Q
0 new mno
1 ffa bat
2 bfg xyz
In [12]:
df.replace(regex=r'^ba.$', value='new')
Out[12]:
P Q
0 new mno
1 ffa new
2 bfg xyz
In [13]:
df.replace(regex={r'^ba.$': 'new', 'ffa': 'xyz'})
Out[13]:
P Q
0 new mno
1 xyz new
2 bfg xyz
In [14]:
df.replace(regex=[r'^ba.$', 'ffa'], value='new')
Out[14]:
P Q
0 new mno
1 new new
2 bfg xyz

Note that when replacing multiple bool or datetime64 objects, the data types in the to_replace
parameter must match the data type of the value being replaced:

In [15]:
s = pd.Series([10, 'p', 'p', 'q', 'p'])

When one uses a dict as the to_replace value, it is like the value(s) in the dict are equal
to the value parameter. s.replace({'p': None}) is equivalent to s.replace(to_replace={'p': None},
value=None, method=None):

In [16]:
s.replace({'p': None})
Out[16]:
0      10
1    None
2    None
3       q
4    None
dtype: object

When value=None and to_replace is a scalar, list or tuple, replace uses the method parameter
(default ‘pad’) to do the replacement. So this is why the ‘p’ values are being replaced by 10 in
rows 1 and 2 and ‘q’ in row 4 in this case. The command s.replace('p', None) is actually equivalent
to s.replace(to_replace='p', value=None, method='pad'):

In [17]:
s.replace('p', None)
Out[17]:
0    10
1    10
2    10
3     q
4     q
dtype: object