Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing parenthesis from a string in pandas with str.replace

Tags:

regex

pandas

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")
like image 361
python_new_user Avatar asked Nov 28 '16 02:11

python_new_user


People also ask

How do I remove parentheses from pandas?

For using regex to remove parentheses from string in Python, we can use the re. sub() or pandas. str. replace() function.

How do you remove parentheses from a string?

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.

How do I remove parentheses from text in Python?

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.

What is regex in pandas replace?

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.


1 Answers

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")
like image 108
Zeugma Avatar answered Oct 14 '22 15:10

Zeugma