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

如何按索引匹配合并两个DataFrame并得到预期结果?

解决方案

你之前的操作参数存在错误:

  • pd.concat没有on参数,它是按轴直接拼接,不适合这种按指定键匹配的场景
  • pd.merge使用axis=1是按列位置拼接,而非按指定列匹配,所以结果不符合预期

正确方法1:使用pd.merge按指定列左连接

直接调用merge方法,指定连接键为index列,连接方式设为left,即可得到目标结果:

import pandas as pd

# 构造示例数据
df1 = pd.DataFrame({'index': [1,2,3,4,5], 'predicted': [1,1,0,0,1]})
df2 = pd.DataFrame({'index': [2,4], 'actual': [1,0]})

# 执行正确的合并操作
result = pd.merge(df1, df2, on='index', how='left')
print(result)

输出结果:

index  predicted  actual
0      1          1     NaN
1      2          1     1.0
2      3          0     NaN
3      4          0     0.0
4      5          1     NaN

正确方法2:将index设为行索引后使用join

如果把两个DataFrame的index列设置为行索引,使用join方法会更简洁:

# 将index列设为行索引
df1.set_index('index', inplace=True)
df2.set_index('index', inplace=True)

# 执行左连接
result = df1.join(df2, how='left')
# 可选:将行索引恢复为列
result.reset_index(inplace=True)
print(result)

输出结果与方法1完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:00:55