how to replace certain value of a dataframe column by iterating

Viewed 55

Good evening please I work on a dataframe of energy consumption of all countries recognized by the UN. my problem is that i want to change the name of some country in the column Energy_df ["Country"]. So I put the countries which I wanted to replace as a key in a dictionary and the new names as values. but when i make my code i notice that only the first name is changed. so I would like to know how to apply it to other country names in the dictionary

# 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()
2 Answers

Use replace of series.

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

Use map to map your dictionary keys to the values:

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
Related