You need to enable JavaScript to run this app. Pandas中用str.contains匹配句子后如何提取匹配词生成新列
优惠活动
大模型
产品
解决方案
定价
更多

Pandas中用str.contains匹配句子后如何提取匹配词生成新列

实现方法

你可以直接使用Pandas内置的str.findall()方法提取所有匹配的关键词,再拼接为逗号分隔的字符串即可,完整实现代码如下:

import pandas as pd
import re

# 你的原有关键词列表
searchfor = ['windows', 'macbook', 'love']
# 拼接正则规则,可选:如果关键词包含./*+?等正则特殊字符,先转义避免匹配异常
searchfor_re = '|'.join(re.escape(word) for word in searchfor)

# 原有逻辑
dataset['Match'] = dataset['sentence'].str.contains(searchfor_re)
dataset['Matchcount'] = dataset['sentence'].str.count(searchfor_re)

# 新增:提取匹配关键词列
dataset['Matched Word'] = dataset['sentence'].str.findall(searchfor_re).str.join(',')

逻辑说明

  • str.findall(searchfor_re) 会逐行扫描句子内容,返回所有匹配到的关键词组成的列表,无匹配则返回空列表
  • str.join(',') 将列表中的多个关键词用逗号拼接为字符串,无匹配则返回空字符串,和你已有的Match、Matchcount字段逻辑完全对齐

可选扩展

如果需要忽略大小写匹配,可给字符串方法添加flags参数:

dataset['Matched Word'] = dataset['sentence'].str.findall(searchfor_re, flags=re.IGNORECASE).str.join(',')

如果需要同一个关键词多次匹配时仅保留一次,可增加去重逻辑:

dataset['Matched Word'] = dataset['sentence'].str.findall(searchfor_re).apply(lambda x: ','.join(set(x)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 10:15:03