You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python正则表达式提取数字+指定关键词并写入Pandas新列

问题描述

我有一个存储字符串文本的Pandas DataFrame,示例如下:

descripton
..32 cars are coming full of attendees..
..64 attendees..
..8 participants are allowed..

需要使用正则表达式提取紧跟指定关键词(participant/participants、attendant/attendees)的数字与关键词组合,预期输出为:

64 attendees
8 participants 

并将结果保存到Pandas的新列中。我尝试了以下代码:

data['affluence0'] = data['description'].str.findall(r'\d+(?= [personnes|participants|membres])')

但该代码会提取列中所有数字及所有指定关键词,我需要仅提取紧跟指定关键词的数字与关键词组合。

解决方案

修正正则表达式

你之前的正则存在两个问题:一是仅捕获数字(用了正向预查(?=)只匹配数字位置),二是关键词分组写法错误([]是字符集,里面的|会被当作普通字符,无法实现“或”逻辑)。要捕获数字+关键词的完整组合,使用以下正则:

r'\d+\s+(attendee[s]?|participant[s]?)'

正则说明:

  • \d+:匹配1个及以上数字
  • \s+:匹配1个及以上空白字符(适配空格、制表符等场景)
  • (attendee[s]?|participant[s]?):匹配attendee/attendees或participant/participants,[s]?表示s为可选字符,覆盖单复数形式

应用到Pandas列

根据每行的匹配数量选择对应方法:

场景1:每行最多1个目标组合

用str.extract直接提取单个匹配项,返回Series格式:

data['affluence0'] = data['description'].str.extract(r'(\d+\s+(attendee[s]?|participant[s]?))', expand=False)

场景2:每行可能存在多个目标组合

用str.findall提取所有匹配项后,用join合并为字符串:

data['affluence0'] = data['description'].str.findall(r'\d+\s+(attendee[s]?|participant[s]?)').str.join(', ')

测试验证

用示例数据测试第一种场景的代码:

import pandas as pd

data = pd.DataFrame({
    'description': [
        '..32 cars are coming full of attendees..',
        '..64 attendees..',
        '..8 participants are allowed..'
    ]
})

data['affluence0'] = data['description'].str.extract(r'(\d+\s+(attendee[s]?|participant[s]?))', expand=False)
print(data['affluence0'])

输出结果:

0    NaN
1    64 attendees
2    8 participants
Name: affluence0, dtype: object

第一行因数字32对应关键词不符合要求,返回NaN,完全符合预期。

内容的提问来源于stack exchange,提问作者Mohamad Serhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:05:25