小编Alv*_*rez的帖子

使用正则表达式提取数据框中括号或数字之前的前导子字符串

我正在寻找一种解决方案来提取没有其他名称或数字的名称。

我的目标是将不在括号中、不带空格和数字的子字符串提取到新列中。

例如:

String                            New string
 Bolivia (Plurinational State of)  Bolivia
 United States of America20        United States of America
Run Code Online (Sandbox Code Playgroud)

数据如下:

**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....
Run Code Online (Sandbox Code Playgroud)

我的代码如下所示:

df['newcontry']=df['Country'].str.extract(r'(\w*\s)')
Run Code Online (Sandbox Code Playgroud)

并返回类似这样的内容:

**Country**                               **Energy Supply**   newcontry
    Antigua and Barbuda                           8000000      Antigua
    Bolivia (Plurinational State of)              50000        Bolivia
    Iran (Islamic Republic of)                    20000        Iran …
Run Code Online (Sandbox Code Playgroud)

python pandas regex-lookarounds

2
推荐指数
1
解决办法
685
查看次数

标签 统计

pandas ×1

python ×1

regex-lookarounds ×1