Extract leading substring before parenthesis or digits in dataframe with regex

Viewed 285

I'm looking for a solution to extract a name without others names or digits.

My goal is to extract the substring not in parentheses, without spaces and digits into a new column.

For example:

String                            New string
 Bolivia (Plurinational State of)  Bolivia
 United States of America20        United States of America

The data looks like this:

**Country**                               **Energy Supply** 
Antigua and Barbuda                           8000000   
Bolivia (Plurinational State of)              50000
Iran (Islamic Republic of)                    20000  
Sint Maarten (Dutch part)                     58000
United States of America20                    65000
China, Macao Special AdministrativeRegion4    52000
.....more cases....                        ....more cases....

My code looks like this:

df['newcontry']=df['Country'].str.extract(r'(\w*\s)')

And returns something like this:

**Country**                               **Energy Supply**   newcontry
    Antigua and Barbuda                           8000000      Antigua
    Bolivia (Plurinational State of)              50000        Bolivia
    Iran (Islamic Republic of)                    20000        Iran
    Sint Maarten (Dutch part)                     58000        Sint
    United States of America20                    65000        United
    China, Macao Special AdministrativeRegion4    52000        China

What can I change in order to solve this error?

2 Answers

Assuming you want the leading chunk of the string only, you can use an alternation group between \d and \(: r"^(.+?) ?(?:\d|\(|$)" and a lazy (.+?) to extract the chunk you're interested in.

>>> df = pd.DataFrame({"Country": ["Bolivia (Plurinational State of)", "United States of America20", "Antigua and Barbuda"]})
>>> df
                            Country
0  Bolivia (Plurinational State of)
1        United States of America20
2               Antigua and Barbuda
>>> df["Country"].str.extract(r"^(.+?) ?(?:\d|\(|$)")
                          0
0                   Bolivia
1  United States of America
2       Antigua and Barbuda

Another option is to replace the end stuff you don't want

df['newcontry']=df['Country'].str.replace(r' ?(?:\(|\d).*', '')
Related