如何通过迭代替换数据框列的特定值

how to replace certain value of a dataframe column by iterating

晚上好,我正在研究联合国认可的所有国家的能源消耗数据框架。 我的问题是我想更改 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()

使用replace系列。

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

使用 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