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

如何匹配DataFrame的两列值到另一DataFrame指定列,匹配成功返回对应survey_id

实现方案

核心逻辑是优先完整匹配「名+空格+姓」的组合,避免单独匹配名或姓出现的误命中情况,完全符合样例要求。

实现步骤

  • 第一步:将调研表的first_name和last_name拼接为完整姓名,生成「完整姓名: survey_id」的映射字典
  • 第二步:构建正则匹配规则,匹配所有调研人员的完整姓名
  • 第三步:遍历投诉表的description字段,匹配到对应完整姓名后映射为survey_id,无匹配则留空

代码示例

import pandas as pd
import re

# 构造样例调研数据
survey_df = pd.DataFrame({
    "survey_id": ["survey1"],
    "first_name": ["John"],
    "last_name": ["Smith"]
})
# 构造样例投诉数据
complaint_df = pd.DataFrame({
    "complaint_number": ["complaint1", "complaint2", "complaint3"],
    "description": ["John Wick is a great movie", "Jason Smith stinks", "John Smith is awesome!"]
})

# 生成完整姓名与survey_id的映射
survey_df['full_name'] = survey_df['first_name'] + ' ' + survey_df['last_name']
name_to_id = dict(zip(survey_df['full_name'], survey_df['survey_id']))

# 构建正则匹配模式,re.escape避免姓名中包含特殊字符影响匹配
pattern = re.compile('|'.join(re.escape(name) for name in name_to_id.keys()))

# 匹配并生成matches列
def get_match(desc):
    match_res = pattern.search(desc)
    return name_to_id[match_res.group()] if match_res else ''

complaint_df['matches'] = complaint_df['description'].apply(get_match)

输出结果验证

运行后得到的投诉表和期望结果完全一致:

complaint_numberdescriptionmatches
complaint1John Wick is a great movie
complaint2Jason Smith stinks
complaint3John Smith is awesome!survey1

如果需要支持同一条投诉描述匹配多个调研人员的场景,只需修改匹配函数即可:

def get_match(desc):
    match_res = pattern.findall(desc)
    return ','.join([name_to_id[name] for name in match_res]) if match_res else ''

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:18:03