如何使用Pandas连接含重复值列的两个表格并生成目标结果?
问题描述
需要将表1和表2连接成表3的样式,使用Pandas的join操作时因连接列存在重复值报错。
表1
| ID | A | B |
|---|---|---|
| 1 | A1 | B1 |
| 2 | A1 | B1 |
| 2 | A2 | B2 |
表2
| ID | Property |
|---|---|
| 1 | Property 1 |
| 1 | Property 2 |
| 2 | Property 1 |
| 2 | Property 2 |
| 2 | Property 3 |
预期输出(表3)
| ID | A | B | Property |
|---|---|---|---|
| 1 | A1 | B1 | Property 1 |
| 1 | A1 | B1 | Property 2 |
| 2 | A1 | B1 | Property 1 |
| 2 | A1 | B1 | Property 2 |
| 2 | A1 | B1 | Property 3 |
| 2 | A2 | B2 | Property 1 |
| 2 | A2 | B2 | Property 2 |
| 2 | A2 | B2 | Property 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
相关产品推荐
相关产品推荐

