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

Python Pandas:如何比较两个DataFrame列并匹配列表中的元素?

解决方法

核心思路是先把df1中存列表的col2拆成单个元素,建立「元素-对应col1值」的映射关系,再和df2做关联匹配。

步骤1:拆分df1的列表列,构建映射表

用explode()方法把df1的col2列表拆成单行元素,同时保留对应的col1值:

import pandas as pd

def function():
    x = {'col1': ['first', 'second'], 'col2': [[1,4,5], [3,6]]}
    y = {'col1': ['X', 'Y', 'Z'], 'col2': [1, 2, 3]}
    df1 = pd.DataFrame(data=x)
    df2 = pd.DataFrame(data=y)
    
    # 拆分df1的列表列,构建映射关系
    mapping = df1.explode('col2').rename(columns={'col1': 'new_col'})
    # 统一col2类型,避免数字/字符串不匹配导致的匹配失败
    mapping['col2'] = mapping['col2'].astype(int)

步骤2:左连接匹配,生成结果

用merge()方法让df2和映射表按col2左连接,自动填充匹配到的new_col,未匹配的会显示NaN:

# 左连接匹配
    result = df2.merge(mapping, on='col2', how='left')
    return result

# 调用函数查看结果
print(function())

输出结果

运行后会得到你想要的格式:

col1  col2 new_col
0    X     1   first
1    Y     2     NaN
2    Z     3  second

适配实际域名场景

如果实际场景中col2是域名(字符串类型),只需要去掉类型转换的代码即可,逻辑完全通用:

# 域名场景下的映射表构建
mapping = df1.explode('col2').rename(columns={'col1': 'new_col'})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:25:33