合并数据帧(python pandas)

问题描述 投票:-1回答:1

我有两个数据帧df1 df1和df2 df2我想使用python pandas合并它们而不创建笛卡尔product.Sample输出看起来像这样output我该怎么做?

目前,我正在使用df3 = pd.merge(df1,df2,on ='id',how ='left'),但它给了我跨产品。结果数据帧df3包含14个id = 1的记录6和8个id = 2。

谢谢,

pandas merge
1个回答
1
投票

您可能需要一个额外的帮助密钥,由cumcount创建

df1['Helpkey']=df1.groupby('id').cumcount()
df2['Helpkey']=df2.groupby('id').cumcount()

df1.merge(df2,how='left').drop('Helpkey',1)
© www.soinside.com 2019 - 2024. All rights reserved.