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)