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

如何在Pandas中为DataFrame的列表列匹配关键词并生成标签列?

从Pandas DataFrame列提取关键词并映射标签

需求说明

现有名为difference的Pandas DataFrame,其中surface-wordings列的取值示例为:

['paths-modified-/clusters/{cluster_id}/hosts/{host_id}/instructions-operations-modified-POST-parameters-modified-body-reply-schema-properties-modified-step_type-enum-deleted']

已定义关键词与标签的映射:

keyword_label_mappings = {
    'POST-parameters-modified': 'POST Parameters Modified',
    'PUT-parameters-modified': 'PUT Parameters Modified',
}

需要从surface-wordings列中匹配关键词,将对应的标签存入新列labels。

实现方法

方法1:使用apply遍历匹配

逻辑直观,适合关键词数量较少的场景:

import pandas as pd

def match_keywords(row):
    # 处理单元格的列表格式,取出目标字符串
    text = row['surface-wordings'][0] if isinstance(row['surface-wordings'], list) else row['surface-wordings']
    matched_labels = []
    for keyword, label in keyword_label_mappings.items():
        if keyword in text:
            matched_labels.append(label)
    # 有匹配返回标签列表,无匹配返回空值
    return matched_labels if matched_labels else pd.NA

# 生成labels列
difference['labels'] = difference.apply(match_keywords, axis=1)

方法2:使用正则表达式批量匹配

关键词数量较多时,正则方式效率更高:

import pandas as pd
import re

# 生成匹配所有关键词的正则模式,自动转义特殊字符
pattern = re.compile('|'.join(re.escape(k) for k in keyword_label_mappings.keys()))

def extract_labels(row):
    text = row['surface-wordings'][0] if isinstance(row['surface-wordings'], list) else row['surface-wordings']
    matched_keywords = pattern.findall(text)
    # 去重后映射为标签
    unique_keywords = list(set(matched_keywords))
    return [keyword_label_mappings[k] for k in unique_keywords] if unique_keywords else pd.NA

difference['labels'] = difference.apply(extract_labels, axis=1)

补充说明

  • 若surface-wordings列的单元格是直接字符串(非列表格式),可删除isinstance判断部分,直接用text = row['surface-wordings']。
  • 若需保留重复出现的关键词匹配结果,去掉set()去重步骤即可。
  • 无匹配项时返回pd.NA,也可根据需求改为空列表[]或其他默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:37:48