如何将一个DataFrame的非空值覆盖到另一个DataFrame中
Pandas 按索引/列名匹配用非空值覆盖DataFrame方案
核心规则
- 以唯一值的行索引(原表首列)、列名(原表首行)作为匹配键
- 完整保留基准表df1的原有行顺序、列顺序、行列总数,不新增/删除任何行、列
- 仅使用待覆盖表df2中的非空值,覆盖df1中对应匹配位置的原有值
- df2中存在但df1没有的行、列直接忽略,不写入结果
实现代码
import pandas as pd # 前置配置:如果你的数据表还没把首列设为行索引,先执行这步 # 执行后首列会作为匹配用的行索引,首行默认作为列名匹配键 df1 = df1.set_index(df1.columns[0]) df2 = df2.set_index(df2.columns[0]) # 核心覆盖逻辑 df_result = df1.copy() # 把df2对齐到df1的行列结构,超出df1范围的行列直接丢弃 df2_aligned = df2.reindex(index=df1.index, columns=df1.columns) # 仅取df2中非空的位置做值覆盖 cover_mask = df2_aligned.notna() df_result[cover_mask] = df2_aligned[cover_mask]
注:如果不需要保留原始df1的数据,可以直接在df1对象上修改,跳过copy步骤即可。
效果验证示例
构造测试用表:
# 基准表df1,结构需要完整保留 df1 = pd.DataFrame({ 'id': ['a', 'b', 'c'], 'score_math': [82, 76, 90], 'score_eng': [68, 88, 79], 'score_phy': [91, 84, 73] }).set_index('id') # 待覆盖表df2,包含空值、df1没有的行和列 df2 = pd.DataFrame({ 'id': ['b', 'c', 'd'], 'score_math': [None, 95, 87], 'score_eng': [92, None, 81], 'score_chem': [77, 69, 85] }).set_index('id')
执行上述代码后得到的结果:
| 行索引 | score_math | score_eng | score_phy |
|---|---|---|---|
| a | 82 | 68 | 91 |
| b | 76 | 92 | 84 |
| c | 95 | 79 | 73 |
结果符合预期:df1原有3行3列结构完全未改动,仅b行英语成绩、c行数学成绩两个位置被df2的非空值覆盖,df2中的空值、多余行d、多余列化学成绩均未对结果产生影响。
内容的提问来源于stack exchange,提问作者Ajit Singh
相关产品推荐
相关产品推荐

