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

Pandas如何合并两个DataFrame以生成对应位置的值元组配对

解决方案

两种实现方式如下,优先推荐第一种,运行效率更高:

方法1:直接列配对拼接(行数完全对齐时使用)

import pandas as pd

# 补充说明后的样例数据
df_1 = pd.DataFrame({'grade' : ['A', 'A', 'B', 'C'], 'score' : [9, 9, 8, 6]})
df_2 = pd.DataFrame({'id' : ['1', '2', '3', '4'] , 'key' : ['5', '6', '7', '8']})

# 逐行配对生成元组
result = pd.DataFrame({
    'grade': list(zip(df_2['id'], df_1['grade'])),
    'score': list(zip(df_2['key'], df_1['score']))
})

print(result)

输出结果:

grade   score
0  (1, A)  (5, 9)
1  (2, A)  (6, 9)
2  (3, B)  (7, 8)
3  (4, C)  (8, 6)

如果是你最初提出的需求(df2两列均为id,输出pair_1、pair_2字段),修改对应列名即可:

df_1 = pd.DataFrame({'grade' : ['A', 'A', 'B', 'C'], 'score' : [9, 9, 8, 6]})
df_2 = pd.DataFrame({'id' : ['1', '2', '3', '4'] , 'id' : ['1', '2', '3', '4']})

result = pd.DataFrame({
    'pair_1': list(zip(df_2['id'], df_1['grade'])),
    'pair_2': list(zip(df_2['id'], df_1['score']))
})

方法2:索引合并后处理(担心行顺序不一致时使用)

先按行索引合并两个表,再通过行处理生成元组:

temp = df_2.join(df_1)
result = pd.DataFrame({
    'grade': temp.apply(lambda x: (x['id'], x['grade']), axis=1),
    'score': temp.apply(lambda x: (x['key'], x['score']), axis=1)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 02:06:04