0

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

2 Answers 2

2

Using pd.Series.map

country_map = {'Republic of Korea': 'South Korea',
               'United States of America20': 'United States of America',
               'United Kingdom of Great Britain and Northern Ireland': 'United Kingdom',
               'China, Hong Kong Special Administrative Region': 'Hong Kong'}

energy['Country'] = energy['Country'].map(country_map)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Yuna A., this is helpful
0

As much as you can, avoid DataFrame.apply which is a hidden loop. Consider vectorized processing such as numpy.select where you pass vectors (i.e., Numpy arrays or Pandas Series) into a method and not scalar elements one at a time:

energy['Country'] = np.select([energy['Country'] == 'South Korea', 
                               energy['Country'] == 'United States', 
                               energy['Country'] == 'United Kingdom', 
                               energy['Country'] == 'Hong Kong'],
                              ['Republic of Korea', 
                               'United States of America', 
                               'United Kingdom of Great Britain and Northern Ireland'
                               'China, Hong Kong Special Administrative Region'])

1 Comment

Thanks all, really helpful suggestions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.