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

如何合并两个Pandas DataFrame,实现同标识行的列数据互补合并?

Pandas DataFrame 合并问题解决方法

问题场景

你有两个示例DataFrame(df1、df2),希望合并后每个ID(列"I")仅保留一行,两个表中的数据在同一行互补展示,缺失值用"00"填充,但使用pd.concat得到的结果出现重复行,不符合预期。

原始数据与预期结果

df1:

import pandas as pd

df1 = pd.DataFrame(
    {
        "I": ["I1","I2", "I3", "I4"],
        "A": ["A0", "A1", "A2", "A3"],
        "B": ["B0", "B1", "B2", "B3"],
        "C": ["C0", "C1", "C2", "C3"],
        "D": ["D0", "D1", "D2", "D3"],
    },
)

df2:

df2 = pd.DataFrame(
    {
        "I":["I1","I4", "I5", "I6", "I7"],
        "E": ["A5", "A6", "A7","A8","A9"],
        "F": ["B5", "B6", "B7","B8","B9"],
        "G": ["C5", "C6", "C7","C8","C9"],
        "H": ["D5", "D6", "D7","D8","D9"],
    },
)

预期结果:

I   A   B   C   D   E   F   G   H
0  I1  A0  B0  C0  D0  A5  B5  C5  D5
1  I2  A1  B1  C1  D1  00  00  00  00
2  I3  A2  B2  C2  D2  00  00  00  00
3  I4  A3  B3  C3  D3  A6  B6  C6  D6
4  I5  00  00  00  00  A7  B7  C7  D7
5  I6  00  00  00  00  A8  B8  C8  D8
6  I7  00  00  00  00  A9  B9  C9  D9

错误原因分析

你之前的代码中,df1.set_index('I')和df2.set_index('I')没有重新赋值,索引并未实际修改;同时pd.concat是纵向拼接两个表,而非按ID匹配合并,导致重复ID出现多行。

正确解决方案

使用pd.merge执行外连接,指定合并键为列"I",之后将缺失值填充为"00",最后按ID排序保持预期顺序:

# 执行外连接合并
df_merged = pd.merge(df1, df2, on="I", how="outer")
# 填充缺失值为"00"
df_merged = df_merged.fillna("00")
# 按预期的ID顺序排序(不需要特定顺序可省略此步骤)
df_merged = df_merged.set_index("I").reindex(["I1", "I2", "I3", "I4", "I5", "I6", "I7"]).reset_index()

print(df_merged)

运行结果

I   A   B   C   D   E   F   G   H
0  I1  A0  B0  C0  D0  A5  B5  C5  D5
1  I2  A1  B1  C1  D1  00  00  00  00
2  I3  A2  B2  C2  D2  00  00  00  00
3  I4  A3  B3  C3  D3  A6  B6  C6  D6
4  I5  00  00  00  00  A7  B7  C7  D7
5  I6  00  00  00  00  A8  B8  C8  D8
6  I7  00  00  00  00  A9  B9  C9  D9

补充说明

  • how="outer"会保留两个表中所有的ID,确保没有数据丢失
  • fillna("00")将合并后出现的缺失值统一替换为"00"
  • reindex用于强制按你预期的ID顺序排列,若无需特定顺序可直接省略

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:05:19