python - Pandas:可以使用 lambda 函数更改列中的名称/反馈

标签 python excel pandas lambda

经过这里的大量帮助和大量的网络搜索,我即将完成我的 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/

相关文章:

python - pandas.DataFrame.sum() 参数 "min_count"相当于 pandas 0.22 之前的版本

python - 在 Python Pandas 的列中为每个 na 填充唯一值

python - 在 Pandas 中,如何从基于另一个数据框的数据框中删除行?

python - 在 Linux 上使用 Python 更改 IP 设置

arrays - 使用特定工作表名称的数组来更新单元格值VBA

vba - Excel VBA 每第 n 行插入分页符

python - Pandas 基础设施数据统计图,每个用户的日期

python - Python 的 Google App Engine utf-8 编码问题

python - 在 python、bash 或 perl 中,如何人为地增加内存

excel - VBA - If 语句引用不同工作表中单元格中的特定文本