Search code examples
pythonpython-3.xpandaspandas-datareader

how to replace certain value of a dataframe column by iterating


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()

Solution

  • Use replace of series.

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