【问题标题】:merging dataframes based on repeating keys in two different dataframes- pandas基于两个不同数据帧中的重复键合并数据帧 - 熊猫
【发布时间】:2019-12-07 15:07:08
【问题描述】:

我有两个数据框 A 和 B,它们属于以下类型

A:
col1    col2    
abc     Pid1     
cdz     Pid1

B:
col2    value
Pid1    2
Pid1    3
Pid1    4

Desired Output:
col1   col2   value
abc    Pid1   2
abc    Pid1   3
abc    Pid1   4
cdz    Pid1   2
cdz    Pid1   3
cdz    Pid1   4

我尝试过合并(外连接),但没有得到想要的结果

请指教

提前谢谢你

【问题讨论】:

  • 使用A.merge(B)
  • Pandas Merging 101的可能重复
  • 除非我不理解合并,但是 col2 上的外部合并应该可以为您提供所需的输出。pd.merge(df,df2,on='col2',how='outer') 在您的示例数据集上为我工作。
  • “我已经尝试过合并(外部连接),但没有得到想要的结果”请添加您的代码,以便我们查看您出错的地方。 merge 肯定是正确答案。

标签: python pandas merge


【解决方案1】:

简单的外部合并:

A = pd.DataFrame({'col1':['abc', 'cdz'], 'col2':['Pid1', 'Pid1']})

print(A)
    col1 col2
0   abc  Pid1
1   cdz  Pid1
B = pd.DataFrame({'col2':['Pid1', 'Pid1','Pid1'], 'value':['2','3','4']})

print(B)

    col2  value
0   Pid1    2
1   Pid1    3
2   Pid1    4
C = A.merge(B, on='col2', how = 'outer', indicator = True)

print(C)

    col1 col2 value _merge
0   abc  Pid1   2    both
1   abc  Pid1   3    both
2   abc  Pid1   4    both
3   cdz  Pid1   2    both
4   cdz  Pid1   3    both
5   cdz  Pid1   4    both

【讨论】:

  • 感谢您的回答。我的错,我使用其他一些数据框粗心的错误生成了一个密钥......还是谢谢你
猜你喜欢
  • 2018-10-12
  • 2017-10-21
  • 2018-09-04
  • 2018-02-11
  • 1970-01-01
  • 2019-10-28
  • 2019-03-05
  • 2020-10-15
相关资源
最近更新 更多