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

编写pandas按指定列合并DataFrame的函数时报KeyError如何解决

错误原因
  • 核心问题是pd.merge()的on参数传入了嵌套列表:你定义的list_to_be_merged_on本身就是存储合并列名的列表,函数内又额外套了一层[],导致实际传入的on值为[['code', 'name', 'section']]。pandas会将外层列表的第一个元素(即完整的列名列表)识别为单个列名,自然找不到对应列,抛出KeyError。
  • 可选排查项:可以确认两个待合并的DataFramefile和car是否确实都存在code、name、section三个列,列名的大小写、前后空格也要保持完全一致。
修复方案

直接去掉函数内on参数额外套的[]即可,修复后代码如下:

import pandas as pd

list_to_be_merged_on = ['code', 'name', 'section']

def merge_on_specific_columns(table1, table2, list_to_be_merged_on):
     merged_table = pd.merge(table1, table2, on=list_to_be_merged_on)
     return merged_table

merged_df = merge_on_specific_columns(file, car, list_to_be_merged_on)

如果需要提升代码鲁棒性,可以增加前置列存在性校验,避免因列缺失抛出模糊的KeyError:

def merge_on_specific_columns(table1, table2, merge_cols):
    # 校验合并列是否存在于两个表中
    missing_in_table1 = [col for col in merge_cols if col not in table1.columns]
    missing_in_table2 = [col for col in merge_cols if col not in table2.columns]
    if missing_in_table1:
        raise ValueError(f"table1中缺少指定合并列:{missing_in_table1}")
    if missing_in_table2:
        raise ValueError(f"table2中缺少指定合并列:{missing_in_table2}")
    return pd.merge(table1, table2, on=merge_cols)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:27:03