pandas 重命名熊猫系列中的某些值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43889944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:34:38 来源:igfitidea点击:
rename certain value in pandas series
提问by feedthemachine
I have the following panda Series:
我有以下Pandas系列:
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.
但它不起作用。
回答by jezrael
You can use if need replace index
:
如果需要替换,您可以使用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:
和replace
列:
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