mardi 11 février 2020

How to apply multiple if/else conditions in a Dataframe using apply and lambda?

I am trying to update certain rows in a column based on a set of conditions. For instance, in the given example below I am trying to update "Country" column names to a shorter version based on a few if statements and here is what I am using. Is there a better way to do this?

energy['Country'] = energy['Country'].apply(lambda x: 'South Korea' if x=='Republic of Korea' 
                        else('United States' if x=='United States of America20' 
                        else('United Kingdom' if x=='United Kingdom of Great Britain and Northern Ireland'
                        else('Hong Kong' if x=='China, Hong Kong Special Administrative Region' 
                             else x))))

Aucun commentaire:

Enregistrer un commentaire