从列表中更改列中的值

2024-04-20 09:01:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有索引“Country”的数据框 我想更改多个国家的名称,我在字典中有旧/新值,如下所示:

我尝试将值从列表和列表中拆分,但这也不起作用。代码没有错误,但我的数据帧中的值没有更改

`import pandas as pd
import numpy as np

energy = (pd.read_excel('Energy Indicators.xls', 
                        skiprows=17, 
                        skip_footer=38))

energy = (energy.drop(energy.columns[[0, 1]], axis=1))
energy.columns = ['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']          
energy['Energy Supply'] = energy['Energy Supply'].apply(lambda x: x*1000000)

#This code isn't working properly
energy['Country'] = energy['Country'].replace({'China, Hong Kong Special Administrative Region':'Hong Kong', 'United Kingdom of Great Britain and Northern Ireland':'United Kingdom', 'Republic of Korea':'South Korea', 'United States of America':'United States', 'Iran (Islamic Republic of)':'Iran'})`

解决:这是我没有注意到的数据问题

energy['Country'] = (energy['Country'].str.replace('\s*\(.*?\)\s*', '').str.replace('\d+',''))

这条线位于“问题”线之下,实际上需要在更换工作开始之前进行清理。美利坚合众国20实际上在excel文件中,所以跳过它

谢谢你的帮助


Tags: columnsof数据import列表asexcelcountry
1条回答
网友
1楼 · 发布于 2024-04-20 09:01:20

您需要通过^{}删除超级脚本:

d = {'China, Hong Kong Special Administrative Region':'Hong Kong', 
     'United Kingdom of Great Britain and Northern Ireland':'United Kingdom', 
     'Republic of Korea':'South Korea', 'United States of America':'United States', 
     'Iran (Islamic Republic of)':'Iran'}

energy['Country'] = energy['Country'].str.replace('\d+', '').replace(d)

您还可以改进您的解决方案-使用参数usecols筛选列,使用参数names设置新列名:

names = ['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']

energy = pd.read_excel('Energy Indicators.xls', 
                        skiprows=17, 
                        skip_footer=38,
                        usecols=range(2,6), 
                        names=names)


d = {'China, Hong Kong Special Administrative Region':'Hong Kong', 
     'United Kingdom of Great Britain and Northern Ireland':'United Kingdom', 
     'Republic of Korea':'South Korea', 'United States of America':'United States', 
     'Iran (Islamic Republic of)':'Iran'}

#for multiple is faster use *
energy['Energy Supply'] = energy['Energy Supply'] * 1000000
energy['Country'] = energy['Country'].str.replace('\d', '').replace(d)
#print (energy)

相关问题 更多 >