0

I would like to replace specific strings within a Pandas Series:

For example, energy['Country'] gives me:

233                             United States of America
234                         United States Virgin Islands
235                                              Uruguay
236                                           Uzbekistan
237                                              Vanuatu
238                                           Venezuela 
239                                             Viet Nam
240                            Wallis and Futuna Islands
241                                                Yemen
242                                               Zambia
243                                             Zimbabwe

However, I would like to replace 'United States of America' with 'United States'.

I have tried using:

energy = energy['Country'].str.replace("United States of America", "United States")

However, this has not worked.

Would anybody be able to give me a helping hand?

1
  • 1
    This should work, maybe there are whitespaces in front? Try energy = energy['Country'].str.strip().str.replace("United States of America", "United States") Commented May 13, 2020 at 19:33

1 Answer 1

1

You basically had it.

energy['Country'] = energy['Country'].str.replace('United States of America', 'United States')

Your original statement makes the dataframe energy equal to the single updated column Country. You just needed to add ['Country'] on the left side of the equals sign to ensure that you are only re-assigning the Country column.

Sign up to request clarification or add additional context in comments.

Comments

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.