简体   繁体   中英

How to edit data in a column in a DataFrame in Pandas using replace method

I am trying to replace few values in the 'Country' Column using DataFrame.replace() method like below. But it's not working. I tried few other ways too, but no luck. Can anyone help me to fix this?

energy = pd.read_excel(r'C:\Users\User\Desktop\New folder\Launchcode\coursera dataScience\course1 week3\Energy Indicators.xls')[16:243]
energy = energy.drop(['Unnamed: 0','Unnamed: 1'], axis = 1).rename(columns={'Environmental Indicators: Energy': 'Country', 'Unnamed: 3': 'Energy Supply', 'Unnamed: 4': 'Energy Supply per Capita', 'Unnamed: 5': '% Renewable'})
energy.replace({"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"}, inplace=True)

您忘记指定列名。

energy.Country.replace({...})

Use the map method

country_map = {
               "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"
    }
energy[column_name] = energy[column_name].map(country_map)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM