Ben Chuanlong Du's Blog

It is never too late to learn.

Replace Values in a pandas DataFrame

Comments

  1. DataFrame.replace works different from DataFrame.update.
In [2]:
import pandas as pd
In [8]:
df = pd.DataFrame({"x": [1, 2, 3, 4, 5], "y": [5, 4, 3, 2, 1]})
df
Out[8]:
x y
0 1 5
1 2 4
2 3 3
3 4 2
4 5 1
In [11]:
df.x[df.x < 3] = 1000
In [12]:
df
Out[12]:
x y
0 1000 5
1 1000 4
2 3 3
3 4 2
4 5 1
In [6]:
df.y.replace(5, 5000, inplace=True)
In [7]:
df
Out[7]:
x y
0 1 5000
1 2 4
2 3 3
3 4 2
4 5 1
In [ ]:
 

Comments