-1

With pd.DataFrame.replace, I have been trying to figure out why the values that I replaced revert back to their original values when I replace another set in another column. How can you make the replacements permanent, below?

titanic.replace({'Pclass' : 
                {3 : 'Lower Class', 
                 2 : 'Middle Class', 
                 1: 'Upper Class'}})
cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    You have to assign the result using titanic = titanic.replace(.... or use parameter inplace = True – Vaishali Aug 31 '17 at 20:58

3 Answers3

3

Read the df.replace documentation:

DataFrame.replace(to_replace=None, value=None, inplace=False, 
                       limit=None, regex=False, method='pad', axis=None)

Replace values given in to_replace with value.


Returns: filled : NDFrame

This isn't an in-place operation unless you specify it to be so.

titanic.replace({'Survived':(0:'False',1:'True')}, inplace=True)

or, assign the return value back.

titanic = titanic.replace({'Survived':(0:'False',1:'True')})

Don't try assigning when inplace=True because then, df.replace returns None.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • thanks. i am very new to programming and it's hard for me to understand the documentation. your answer here helped a lot though. – techscolasticus Sep 02 '17 at 18:14
  • @techscolasticus If my answer helped, you can mark it accepted. Thank you. – cs95 Sep 02 '17 at 20:00
  • @coldspeed. I tried marking it as accepted but then it removes the mark from Daniel H's answer which was a bit easier for me to understand why my original method didn't work. – techscolasticus Sep 02 '17 at 20:04
3

add inplace =True

titanic.replace({'Survived':(0:'False',1:'True')},inplace =True)

Also for kaggle titanic data, recommend map

d={0:'False',1:'True'}

titanic.Survived=titanic.Survived.map(d)
BENY
  • 317,841
  • 20
  • 164
  • 234
  • what does map do? sorry, i'm very new to programming in general and have trouble understanding pandas documentation. – techscolasticus Sep 02 '17 at 18:12
  • @techscolasticus think about 'map' is 'merge', In your example , If value =0 after map it will return `False`, just like a dictionary , 0-->False – BENY Sep 02 '17 at 18:14
0

The code titanic.replace(...) creates a new DataFrame, and returns that. In order to have Python remember this DataFrame later instead of just getting rid of it, you need to assign it to something, with df = titatic.replace(...). Here df can be any name, including titanic; if you use the same name, it will get rid of the old DataFrame and use the new one from then on.

Daniel H
  • 7,223
  • 2
  • 26
  • 41