Sacha Gunaratne
Sacha Gunaratne

Reputation: 56

Why doesn't calling replace on a pandas dataFrame not act on the original object?

If you look at the following simple example:

import pandas as pd 
l1 = [1,2,'?']
df = pd.DataFrame(l1)
df.replace('?',3)

Why does this not replace the '?' in the dataframe df? Wouldn't the object that is referred to by df be affected when replace is called on it?

If I write:

df = df.replace('?',3)

Then df.replace returns a new dataFrame that has replaced the value of ? with 3.

I'm just confused as to why a function that acts on an object can't change the object itself.

Upvotes: 1

Views: 50

Answers (1)

jezrael
jezrael

Reputation: 863186

You need inplace=True:

df.replace('?',3, inplace=True)
print (df)
   0
0  1
1  2
2  3

Upvotes: 3

Related Questions