'rename certain value in pandas series
I have the following panda Series:
print(df.head())
Country Energy Supply Energy Supply per Capita % Renewable
0 Afghanistan 3.210000e+08 10 78.669280
1 Albania 1.020000e+08 35 100.000000
2 Algeria 1.959000e+09 51 0.551010
3 American Samoa NaN ... 0.641026
4 Andorra 9.000000e+06 121 88.695650
How can I rename Afghanistan to Afghanistan_new? I can set the index:
df = df.set_index('Country')
and then try to rename the country the following way:
df['Afghanistan'].rename('Afghanistan_renamed')
but it doesn't work.
Solution 1:[1]
You can use if need replace index
:
df = df.set_index('Country')
df = df.rename(index={'Afghanistan':'Afghanistan_renamed'})
print (df)
Energy Supply Energy Supply per Capita % Renewable
Country
Afghanistan_renamed 3.210000e+08 10 78.669280
Albania 1.020000e+08 35 100.000000
Algeria 1.959000e+09 51 0.551010
American Samoa NaN ... 0.641026
Andorra 9.000000e+06 121 88.695650
and for replace
column:
df['Country'] = df['Country'].replace({'Afghanistan':'Afghanistan_renamed'})
df = df.set_index('Country')
print (df)
Energy Supply Energy Supply per Capita % Renewable
Country
Afghanistan_renamed 3.210000e+08 10 78.669280
Albania 1.020000e+08 35 100.000000
Algeria 1.959000e+09 51 0.551010
American Samoa NaN ... 0.641026
Andorra 9.000000e+06 121 88.695650
Solution 2:[2]
You can just use replace() instead rename():
df['Country'].replace({'Afghanistan':'Afghanistan_renamed'}, inplace=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jezrael |
Solution 2 | Ernest |