重命名熊猫系列中的某个值

时间:2017-05-10 10:32:31

标签: python pandas series

我有以下熊猫系列:

weak

如何将阿富汗重新命名为阿富汗? 我可以设置索引:

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

然后尝试按以下方式重命名国家/地区:

df = df.set_index('Country')

但它没有用。

1 个答案:

答案 0 :(得分:6)

如果需要替换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

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