pandas - 更改列表中列中的值

标签 pandas dataframe replace rename

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

我尝试拆分 from 列表和 to 列表中的值,但这也不起作用。代码没有错误,但我的数据框中的值没有改变。

`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+',''))

该行位于“问题”行下方,而实际上需要在替换工作之前对其进行清理。例如。 United States of America20 实际上在 Excel 文件中,因此替换跳过了它

感谢您的帮助!!

最佳答案

您需要通过 replace 删除上标:

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)

关于pandas - 更改列表中列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43310228/

相关文章:

python - 如何对任意数量的分类变量实现分层 K 折 split ?

python - Replace() 没有找到日期,也没有转换为另一个字符串

python - 在Python中处理数据集中的缺失值

R dplyr : change the row value of columns having an specific name

jQuery 编程风格?

Java : replacing text URL with clickable HTML link

python - 使用 Python/Pandas 处理嵌套在 JSON 中的 JSON

python - 如何在 Python 中替换数据框中的子字符串

Python Pandas 使用滚动时间窗口进行计数

vba - VBA : Search, save and replace by rows according to conditions