首页 > 解决方案 > 如何使用 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)

我尝试过的#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)

已知问题:

谢谢!

标签: regexpandas

解决方案


您可以使用

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

推荐阅读