经过这里的大量帮助和大量的网络搜索,我即将完成我的 Cousera 数据科学作业的一部分(共 10 部分)。但由于我对 Python 和 Pandas 相对缺乏经验,我有一种烦人的感觉,即问题本可以更好地解决。
任务:从此处导入 Excel 列表:http://unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls
删除国家名称中带有“(”的数字和所有内容。
重命名某些国家名称(在字典中)
这是有效的代码。我本可以做得更好/更有效率?
energy=pd.read_excel('Energy Indicators.xls',
sheetname='Energy',
skiprows=[17],
skipfooter=38,
header=15,
index_col=[0],
usecols=[2,3,4,5]
)
energy.index.names=['Country']
energy.rename(columns={'Renewable Electricity Production': '% Renewable'}, inplace=True)
energy=energy.reset_index()
energy.Country=energy.Country.replace(to_replace='\d',value='', regex=True)
energy.Country=energy.Country.replace(to_replace='( \()(.*)(\))',value='', regex=True)
#energy.Country=energy.Country.replace(to_replace='(\.){3}',value='None', regex=True)
dicts = {"Republic of Korea": "South Korea",
"United States of America": "United States",
"United Kingdom of Great Britain and Northern Ireland": "United Kingdom",
"China, Hong Kong Special Administrative Region": "Hong Kong"}
for x in dicts.keys():
energy.Country.loc[lambda s: s==x]=dicts[x]
最佳答案
好吧,pandas 已经为此提供了一个内置函数:
energy.Country.replace(dicts, inplace=True)
关于python - Pandas:可以使用 lambda 函数更改列中的名称/反馈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47021836/