首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于关键字的pandas文本抽取

基于关键字的pandas文本抽取
EN

Stack Overflow用户
提问于 2017-11-11 03:00:46
回答 1查看 323关注 0票数 0

我有一个包含两列的数据集:

代码语言:javascript
复制
Index            Text
 1               *some text* address13/b srs mall, indirapuram,sann-444000 *some text*
 2               *some text*   
 3               *some text* contactus 12J 1st floor, jajan,totl-996633 *some text*
 4               ..........
 5               ........

我想要一个数据帧有一个新的列作为“位置”,其中只有该字符串将从列“文本”中提取的关键字“地址”或“联系人”,直到6位数字,并给出"NA“,其中字符串不匹配。输出我想要的内容如下:

代码语言:javascript
复制
Index                location
1                 13/b srs mall, indirapuram,sann-444000
2                 NA
3                 12J 1st floor, jajan,totl-996633
4                 NA
EN

回答 1

Stack Overflow用户

发布于 2017-11-11 03:06:33

使用str.extract

代码语言:javascript
复制
df['location'] = df.Text.str.extract('(?:address|contactus)(.*?\d{6})', expand=False)
df.drop('Text', 1)

   Index                                location
0      1  13/b srs mall, indirapuram,sann-444000
1      2                                     NaN
2      3        12J 1st floor, jajan,totl-996633

另外,当您有多个项目需要检查时,可以将它们放在一个列表中,并使用str.join将它们连接起来

代码语言:javascript
复制
terms = ['address', 'contactus', ...]

df['location'] = df.Text.str\
         .extract(r'(?:{})(.*?\d{6})'.format('|'.join(terms), expand=False)

正则表达式详细信息

代码语言:javascript
复制
(?:        # non-capturing group
address    # "address" 
|          # regex OR
contactus  # "contactus
)  
(.*?       # non-greedy match-all
\d{6}      # 6 digit zipcode
)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47229501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档