regex - 如何使用 Pandas 组合独立的正则表达式并将它们应用于数据集的所有行?
问题描述
问题陈述:
我有两个单独的正则表达式,我试图将它们“组合”成一个并应用于数据集中的每一行。每行的匹配部分应转到名为“Wanted”的新 Pandas 数据框列。请参阅下面的示例数据,了解匹配的值应如何在“通缉”列中格式化。
示例数据(我希望它看起来如何):
列0 | 想要(希望“Column0”看起来像这样) |
---|---|
爱丽丝\t12-345-623/ 10-1234 | 爱丽丝,12-345-623、10-1234 |
鲍勃 201-888-697 / 12-0556a | 鲍勃,201-888-697、12-0556a |
蒂姆 073-110-101 / 13-1290 | 蒂姆,073-110-101、13-1290 |
乔 74-111-333/ 33-1290 和 Amy(12-345-623)/10-1234c | 乔, 74-111-333, 33-1290, 艾米, 12-345-623, 10-1234c |
换句话说...:
2-3 位 ----- 连字符 ---- 3 位 --- 连字符 ---- 3 位 ---- 任何字符 ---- 2 位 --- 连字符 --- 4 位 --- - 允许一个字符
我尝试过的#1:
在闲逛了一段时间后,我想出了两个不同的正则表达式,它们可以单独解决部分问题。有点。
这将匹配每行中的第一组数字(但没有得到第二组 - 我想要的)我对我尝试过的感兴趣。不过,我不确定这有多强大。
示例问题行 (regex = r"(?:\d{1,3}-){0,3}\d{1,3}")
search_in = "Alice\t12-345-623/ 10-1234"
wanted_regex = r"(?:\d{1,3}\-){0,3}\d{1,3}"
match = re.search(wanted_regex, search_in)
match.group(0)
- 通缉:爱丽丝,12-345-623、10-1234
- Got: 12-345-623 # 匹配数字组,但格式不符合我的要求(参见示例数据)
我尝试过的#2:
- 这将匹配每一行的第二部分——但是!--- 仅当它是列中的唯一值时。我遇到的问题是它匹配第一组数字而不是第二组。
Example Problem Row (regex = r"(?:\d{2,3}-){1}\d{3,4}") # 与上面不同的正则表达式!
search_in = "Alice\t12-345-623/ 10-1234"
wanted_regex = r"(?:\d{2,3}\-){1}\d{3,4}"
match = re.search(wanted_regex, search_in)
match.group(0)
- 通缉:爱丽丝,12-345-623、10-1234
- Got: 12-345 # 在第一部分匹配
已知问题:
- 当我尝试“Alice\t12-345-623/ 10-1234”时,当我尝试匹配“10-1234”时,它将匹配“12-345”
谢谢!
- 提前感谢所有愿意帮助我解决这个问题的巫师。对此,我真的非常感激:)
- 注意:我已经询问过可能使解决这个问题更容易的正则表达式。可能不是,但无论如何这里是链接->如何使用正则表达式选择一行以及在熊猫数据框中包含特定子字符串的行之后的固定数量的行
解决方案
您可以使用
re.sub(r'\s*\band\b\s*|[^\w-]+', ', ', text)
请参阅正则表达式演示。
熊猫版:
df['Wanted'] = df['Column0'].str.replace(r'\s*\band\b\s*|[^\w-]+', ', ', regex=True)
详情:
\s*\band\b\s*
-用可选的零个或多个空白字符包围的整个单词(\b
是单词边界)and
|
- 或者[^\w-]+
- 一个或多个字符,而不是字母、数字_
和-
查看Python 演示:
import re
texts = ['Alice 12-345-623/ 10-1234',
'Bob 201-888-697 / 12-0556a','Tim 073-110-101 / 13-1290',
'Joe 74-111-333/ 33-1290 and Amy(12-345-623)/10-1234c']
for text in texts:
print(re.sub(r'\s*\band\b\s*|[^\w-]+', ', ', text))
# => Alice, 12-345-623, 10-1234
# Bob, 201-888-697, 12-0556a
# Tim, 073-110-101, 13-1290
# Joe, 74-111-333, 33-1290, Amy, 12-345-623, 10-1234c
推荐阅读
- azure-devops - 如何创建数组 | 在 Azure Pipelines (.yml) 中动态列出
- reactjs - 如何更改我在 ReactJS 中动态状态的余额
- kubernetes - Kubernetes入口到在同一主机上运行的pod?
- jdbc - 使用 JDBC 的 db2 load 命令失败
- python - 如何将网页中的数据获取到 iseries 并使用 Python 处理它
- kubernetes - 我可以在集群中使用不同版本的 cassandra 吗?
- node.js - Twilio 在 Firebase 云功能中不起作用
- javascript - 搜索 MySQL & PHP 生成的 UL
- python - 用于多个不同类型数组的 Numpy.i 类型映射
- dynamics-ax-2012-r3 - 学习批处理作业参数 AX 2012