如何通过迭代替换数据框列的某些值

问题描述 投票:2回答:2

[晚上好,我正在研究联合国认可的所有国家的能源消耗数据框架。我的问题是我想在Energy_df [“ Country”]列中更改某个国家的名称。所以我把我要替换的国家/地区作为字典中的键,而新名称则作为值。但是当我编写代码时,我注意到只有名字被更改了。因此我想知道如何将其应用于字典中的其他国家/地区名称

# Energy_df["Country"] is the dataset column which I want to replace certain country name 

newname={"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"}

def answer():
    for name in Energy_df["Country"]:
        if name in newname.key():
            Energy_df["Country"].replace(newname[name],inplace=True)
        else:
            continue
    return Energy_df["Country"]
answer()
python python-3.x pandas pandas-datareader
2个回答
1
投票

使用系列的replace

df['Country'] = df['Country'].replace(newname)

1
投票

使用map将字典键映射到值:

newname={"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"}

df = pd.DataFrame([{
    'Country': "Republic of Korea"
},{
    'Country': "United States of America"
}])
print(df.head())
#                     Country
# 0         Republic of Korea
# 1  United States of America
df['Country'] = df['Country'].map(newname)
print(df.head())
#          Country
# 0    South Korea
# 1  United States
© www.soinside.com 2019 - 2024. All rights reserved.