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

Pandas匹配DataFrame列表列与另一DataFrame列的子串问题

问题定位

你遇到的问题主要由两点导致:

  • 列名大小写不匹配:你定义df时指定的列名为First(首字母大写),但两次代码里都写成了小写的first,pandas无法识别对应列,自然无法完成匹配
  • 返回逻辑不符合需求:你在循环里直接用return,只要匹配到第一个结果就会终止函数运行,无法拿到所有符合条件的字符串
  • 额外优化点:你将列表拼接为字符串再用str.contains匹配的方式存在子串误匹配风险,比如目标关键词是First,如果有列表元素为Firstx也会被误判,直接提取关键词匹配更准确

修复后可运行代码

import pandas as pd

# 原始数据定义
data = {'First':  [['First', 'value'],['second','value'],['third','value','is'],['fourth','value','is']],
'Second': [['adj','noun'],['adj','noun'],['adj','noun','verb'],['adj','noun','verb']]}
df = pd.DataFrame(data, columns = ['First','Second'])

data2 = {'example':  ['First value is important', 'second value is imprtant too','it us goof to know']}
df2 = pd.DataFrame(data2, columns = ['example'])

def reader():
    # 提前提取df的First列所有子列表的首个元素,生成匹配集合提高查询效率
    match_keywords = set(item[0] for item in df['First'])
    match_result = []
    for example_str in df2['example']:
        # 提取当前字符串的首个单词
        first_word = example_str.split(' ', 1)[0]
        if first_word in match_keywords:
            match_result.append(example_str)
    return match_result

# 调用函数获取结果
print(reader())

输出结果

['First value is important', 'second value is imprtant too']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:15:03