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

如何使用Pandas连接含重复值列的两个表格并生成目标结果?

问题描述

需要将表1和表2连接成表3的样式,使用Pandas的join操作时因连接列存在重复值报错。

表1

IDAB
1A1B1
2A1B1
2A2B2

表2

IDProperty
1Property 1
1Property 2
2Property 1
2Property 2
2Property 3

预期输出(表3)

IDABProperty
1A1B1Property 1
1A1B1Property 2
2A1B1Property 1
2A1B1Property 2
2A1B1Property 3
2A2B2Property 1
2A2B2Property 2
2A2B2Property 3

解决方案

你要的是按ID列的多对多连接,Pandas的join方法默认按索引连接,在连接列有重复值时容易引发歧义报错,改用merge方法可直接实现需求:

代码示例

import pandas as pd

# 构造表1的DataFrame
df1 = pd.DataFrame({
    'ID': [1, 2, 2],
    'A': ['A1', 'A1', 'A2'],
    'B': ['B1', 'B1', 'B2']
})

# 构造表2的DataFrame
df2 = pd.DataFrame({
    'ID': [1, 1, 2, 2, 2],
    'Property': ['Property 1', 'Property 2', 'Property 1', 'Property 2', 'Property 3']
})

# 按ID执行多对多连接
result_df = pd.merge(df1, df2, on='ID')

print(result_df)

说明

  • pd.merge默认支持多对多连接逻辑:对每个ID值,将表1中该ID的所有行与表2中该ID的所有行做笛卡尔积组合,完全匹配预期输出格式。
  • 避开join是因为它默认以索引为连接键,当索引或连接列存在重复值时,会因匹配关系不明确报错,而merge可直接指定业务列作为连接键,更适配这类场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 13:30:12