1

I am learning Pandas Dataframe from here. I came across method replace(). Firstly a DataFrame df is defined which has following values:

     Student1 Student2  Student3
0          OK  Perfect  Acceptable
1       Awful    Awful     Perfect
2  Acceptable       OK        Poor

The tutorial asks to do the following :

df.replace(['Awful', 'Poor', 'OK', 'Acceptable', 'Perfect'], [0, 1, 2, 3, 4])

After running that line of code, when I run print(df), I still get the same result which is:

     Student1 Student2    Student3
0          OK  Perfect  Acceptable
1       Awful    Awful     Perfect
2  Acceptable       OK        Poor

When I searched for this method on stackoverflow, I came to know the correct line of code should be:

df['Student1']=df['Student1'].replace(['Awful', 'Poor', 'OK', 'Acceptable', 'Perfect'], [0, 1, 2, 3, 4])

That updates only the column 'Student1'. So if I have, say 20 columns, then would I need to replace values in all 20 columns manually or is there a better way to replace all values at once?

Many Thanks.

Edit:

The solution mentioned in the comment @jezrael worked for me.

df.replace(['Awful', 'Poor', 'OK', 'Acceptable', 'Perfect'], [0, 1, 2, 3, 4],inplace=True)
Ayush Goyal
  • 233
  • 1
  • 11
  • 3
    You need assign back `df = df.replace(['Awful', 'Poor', 'OK', 'Acceptable', 'Perfect'], [0, 1, 2, 3, 4])` or `df.replace(['Awful', 'Poor', 'OK', 'Acceptable', 'Perfect'], [0, 1, 2, 3, 4], inplace=True)` – jezrael Mar 25 '18 at 07:00
  • Untlis unless you are using `inplace` or assigning back to `df`, you are just changing a view of the dataframe – enterML Mar 25 '18 at 07:01
  • 1
    Thank you @jezrael . This worked for me. – Ayush Goyal Mar 25 '18 at 07:03

0 Answers0