![](/img/trans.png)
[英]Regex to match string which has words followed by whitespace then digits dot or hyphen and words followed by space and then (some info)
[英]Extract part of a string with regex before hyphen followed by digits
我有一个数据框test
其中的列category
包含单词,字符和数字的复杂模式。 我需要将由连字符分隔的单词先提取,然后再将数字提取到新列sub_category
。
我不是正则表达式专家,所以花了很多时间与之抗争。 因此,将感谢您的帮助!
test = pd.DataFrame({
'id': ['1','2','3','4'],
'category': ['worda-wordb-1234.ds.er89.',
'worda-4567.we.77-ty','wordc-wordd-5698/de/','wordc-2356/rt/']
})
所需的输出:
id category sub_category
0 1 worda-wordb-1234.ds.er worda-wordb
1 2 worda-4567.we.ty worda
2 3 wordc-wordd-5698/de/ wordc-wordd
3 4 wordc-2356/rt/ wordc
使用str.extract,
test['sub-category'] = test.category.str.extract('(.*)-\d+')
id category sub-category
0 1 worda-wordb-1234.ds.er89. worda-wordb
1 2 worda-4567.we.77-ty worda
2 3 wordc-wordd-5698/de/ wordc-wordd
3 4 wordc-2356/rt/ wordc
您想要的只是字符串的开头和尽可能多的非数字,最后一个连字符除外。 这应该可以解决问题:
^\D+?(?=-\d)
说明:
^
匹配字符串的开头 \\D+?
匹配非数字,但以非贪婪方式 (?=-\\d)
匹配连字符后跟数字; 这迫使上一场比赛停止。 您也可以使用split()
做到这一点:
>>> df
id category
0 1 worda-wordb-1234.ds.er89.
1 2 worda-4567.we.77-ty
2 3 wordc-wordd-5698/de/
3 4 wordc-2356/rt/
结果输出:
>>> df['sub_category'] = df.category.str.split('-\d+',expand=True)[0]
>>> df
id category sub_category
0 1 worda-wordb-1234.ds.er89. worda-wordb
1 2 worda-4567.we.77-ty worda
2 3 wordc-wordd-5698/de/ wordc-wordd
3 4 wordc-2356/rt/ wordc
或,如@jezrael在split()方法中建议的那样,几乎没有什么变化,它指定了数据集所需的分割数,此处仅此一个...
df['sub_category'] = df.category.str.split('-\d+',n=1).str[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.