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

如何在Python pandas中实现匹配后返回另一列值的查找功能

解决方案

核心思路是先建立窄术语→宽术语的映射关系,再将匹配到的窄术语替换为对应的宽术语即可,完整实现代码如下:


基础版本(适配初始测试用例)

import pandas as pd

# 原测试数据
df = pd.DataFrame({'Name':['a cat', 'grey puppy', 'red dog']})
df2 = pd.DataFrame({'BroadTerm':['cat', 'cat', 'dog', 'dog'], 'NarrowTerm':['cat', 'kitten', 'puppy', 'dog']})

# 第一步:构建窄术语到宽术语的唯一映射字典
term_map = df2.drop_duplicates('NarrowTerm').set_index('NarrowTerm')['BroadTerm'].to_dict()

# 第二步:匹配Name列中的窄术语,映射为宽术语并去重拼接
df['Animal'] = df['Name'].apply(lambda x: ','.join(
    {term_map[term] for term in term_map if term in x}
))

print(df)

运行输出与预期完全一致:

Name Animal
0       a cat    cat
1  grey puppy    dog
2     red dog    dog

适配更新后的测试数据集版本

import pandas as pd
import numpy as np

# 更新后的测试数据
df = pd.DataFrame({'Name':['a cat dog - multiple', 'grey puppy - narrow term', 'a cat puppy', 'reddog - single no spaces', 'acatdog - multiple no spaces']})
df2 = pd.DataFrame({'BroadTerm':['cat', 'cat', 'dog', 'dog'], 'NarrowTerm':['cat', 'kitten', 'puppy', 'dog']})

term_map = df2.drop_duplicates('NarrowTerm').set_index('NarrowTerm')['BroadTerm'].to_dict()

df['Animal'] = df['Name'].apply(lambda x: ','.join(
    {term_map[term] for term in term_map if term in x}
))

# 可选配置:无匹配结果时替换为NaN而非空字符串
df['Animal'] = df['Animal'].replace('', np.nan)

print(df)

运行输出:

Name  Animal
0          a cat dog - multiple  cat,dog
1      grey puppy - narrow term     dog
2                   a cat puppy  cat,dog
3     reddog - single no spaces     dog
4  acatdog - multiple no spaces  cat,dog

注意说明

  • 单文本命中多个对应不同宽术语的窄术语时,会用逗号拼接所有匹配结果
  • 匹配逻辑为子字符串模糊匹配,无需空格分隔,reddog这类无间隔文本也能正常命中
  • 用集合存储匹配结果自动去重,避免同一宽术语对应多个窄术语时重复输出

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 14:15:04