如何匹配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_number | description | matches |
|---|---|---|
| complaint1 | John Wick is a great movie | |
| complaint2 | Jason Smith stinks | |
| complaint3 | John 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
相关产品推荐
相关产品推荐

