晚上好,我正在研究联合国认可的所有国家的能源消耗数据框架。 我的问题是我想在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()
答案 0 :(得分:1)
使用系列的replace
。
df['Country'] = df['Country'].replace(newname)
答案 1 :(得分: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