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

Pandas合并两个DataFrame时触发KeyError问题求助

问题原因分析

嘿,你遇到的KeyError其实逻辑上很好理解——ids_of_new_rows是Input表存在但Master表完全没有的ID,你却试图从masterDf里定位这些ID对应的行,Master里本来就没这些数据,自然会报错找不到索引啦!

修正方案

你需要从inputDf里提取这些新增行,而不是反过来从masterDf里找。下面是修正后的完整代码:

import pandas as pd

# 读取数据并设置ID为索引
inputDf = pd.read_excel(inputFileName).set_index("ID")
masterDf = pd.read_excel(masterFileName).set_index("ID")

# 1. 更新Master中已有的行数据(这部分你的代码是对的)
masterDf.update(inputDf)

# 2. 找出Input有但Master没有的ID集合
ids_of_new_rows = set(inputDf.index) - set(masterDf.index)

# 3. 从Input中提取新增行,只保留和Master共有的列(避免列不匹配)
rows_to_add = inputDf.loc[ids_of_new_rows, inputDf.columns & masterDf.columns]

# 4. 将新增行合并到Master中
masterDf = pd.concat([masterDf, rows_to_add])

# 可选:如果需要把ID从索引变回普通列
# masterDf = masterDf.reset_index()

# 保存更新后的Master表
masterDf.to_excel(masterFileName)
额外优化建议

其实pandas有更简洁的方法可以一步完成「更新已有行+新增缺失行」的需求,推荐两种方式:

方法1:使用combine_first(最简洁)

这个方法会优先用inputDf的数据覆盖masterDf对应索引和列的值,同时自动保留masterDf独有的列、添加inputDf的新增行:

inputDf = pd.read_excel(inputFileName).set_index("ID")
masterDf = pd.read_excel(masterFileName).set_index("ID")

# 一步完成更新+新增
updated_master = inputDf.combine_first(masterDf)

updated_master.to_excel(masterFileName)

方法2:使用外连接merge(更灵活)

如果需要精细控制列的保留逻辑,可以用外连接后再更新:

inputDf = pd.read_excel(inputFileName).set_index("ID")
masterDf = pd.read_excel(masterFileName).set_index("ID")

# 外连接获取所有行和列,区分Input和Master的同名列
merged_df = pd.merge(masterDf, inputDf, left_index=True, right_index=True, how='outer', suffixes=('', '_input'))

# 用Input的数据覆盖Master对应列的值
for col in masterDf.columns:
    if f"{col}_input" in merged_df.columns:
        merged_df[col] = merged_df[f"{col}_input"].combine_first(merged_df[col])
        merged_df.drop(f"{col}_input", axis=1, inplace=True)

merged_df.to_excel(masterFileName)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:22:48