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

如何用Pandas合并行列数均不同且有公共索引列的DataFrame

合并行列不同的DataFrame(保留所有行和列)

构造测试数据

import pandas as pd

df1 = pd.DataFrame({'A': [1,2,4], 'B': [0,3,5], 'C': [0,4,6]}, index=['a','b','c'])
df2 = pd.DataFrame({'A': [1,2,1,1], 'C': [0,4,4,2], 'D': [2,2,5,3], 'E': [3,4,6,4]}, index=['a','b','d','e'])

解决方案

使用pd.merge实现全外连接,指定按索引匹配,同时处理重复列:

# 按索引全外连接,重复列自动加后缀
merged = pd.merge(df1, df2, how='outer', left_index=True, right_index=True)
# 合并重复的A、C列(取非空值,示例中相同索引值一致,直接合并)
merged['A'] = merged['A_x'].fillna(merged['A_y'])
merged['C'] = merged['C_x'].fillna(merged['C_y'])
# 删除冗余列,调整列顺序
final = merged.drop(columns=['A_x','A_y','C_x','C_y'])[['A','B','C','D','E']]

输出结果:

A    B  C    D    E
a  1.0  0.0  0  2.0  3.0
b  2.0  3.0  4  2.0  4.0
c  4.0  5.0  6  NaN  NaN
d  1.0  NaN  4  5.0  6.0
e  1.0  NaN  2  3.0  4.0

失败原因分析

  • join:默认左连接,仅保留左表行,需手动指定how='outer'且处理重复列;
  • merge:默认按列名匹配(非索引)+内连接,仅保留共同行,需显式开启索引匹配和外连接;
  • concat(axis=1):按索引列合并,但重复列会保留两份,需额外合并逻辑。

内容的提问来源于stack exchange,提问作者Chang Woon Jang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:35:48