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

如何合并两个pandas DataFrame 按列1匹配填充缺失值

pandas按指定列匹配填充缺失值实现方案

核心需求

以第1列为匹配键,用存储有效值的小表df1,填充全量大表df2中对应位置的空值,最终保留df2的全部行与列结构。

方法1:通用全列填充(推荐)

使用combine_first方法按索引对齐填充,适合需要同时填充多列的场景,代码最简洁:

import pandas as pd

# 初始化测试数据
d1 = {1:['Test','Test1','Test2'], 2:['A','B','C']}
d2 = {1:['Something','Test','Test1','Test2','Test3','Test4'], 2:['z',None,None,None,'x','y'],3:['Blah','Blah','Blah','Blah','Blah','Blah']}
df1 = pd.DataFrame(data=d1)
df2 = pd.DataFrame(data=d2)

# 匹配键设为索引 -> 按规则填充 -> 还原匹配键为普通列
result = df2.set_index(1).combine_first(df1.set_index(1)).reset_index()

实现逻辑说明

  • 先将作为匹配键的第1列设置为行索引,强制pandas按匹配键对齐两个表的行数据
  • combine_first的填充规则为:优先保留调用方(df2)的非空值,仅当df2对应位置为空时,才取df1的对应值填充,完全匹配需求
  • 填充完成后用reset_index()将第1列从索引还原为普通列,得到标准表结构

方法2:指定列填充

如果仅需要填充特定列,可以用映射字典匹配填充,逻辑更直观:

result = df2.copy()
# 生成 匹配键->待填充值 的映射字典
fill_map = df1.set_index(1)[2].to_dict()
# 筛选出目标列空值的行,用映射值替换
result.loc[result[2].isna(), 2] = result[result[2].isna()][1].map(fill_map)

输出结果

两种方法运行后得到的result完全符合预期:

1  2     3
0  Something  z  Blah
1       Test  A  Blah
2      Test1  B  Blah
3      Test2  C  Blah
4      Test3  x  Blah
5      Test4  y  Blah

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 17:43:13