I have a list of countries where some have a space and parenthesis after, for example, "Bolivia (Plurinational State of)".
Why doesn't my code below work to only keep "Bolivia"?
energy['Country'] = energy['Country'].str.replace("Bolivia (Plurinational State of)","Bolivia")
For using regex to remove parentheses from string in Python, we can use the re. sub() or pandas. str. replace() function.
sub() function to remove parentheses from a string. We removed parentheses from our string variable using the re. sub() function in the code above. We achieved our goal by replacing the opening and closing parentheses with an empty string and storing the return value inside our original string.
To remove parentheses from string using Python, the easiest way is to use the Python sub() function from the re module. If your parentheses are on the beginning and end of your string, you can also use the strip() function.
regex: It checks whether to interpret to_replace and/or value as regular expressions. If it is True, then to_replace must be a string. Otherwise, to_replace must be None because this parameter will be interpreted as a regular expression or a list, dict, or array of regular expressions.
str.replace
uses regex to perform replacements. The parentheses must be escaped to keep them as simple characters:
energy['Country'].str.replace("Bolivia \(Plurinational State of\)","Bolivia")
You can automate escaping like this:
import re
energy['Country'].str.replace(re.escape('Bolivia (Plurinational State of)'),"Bolivia")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With