数据框按行合并

时间:2019-10-16 19:30:56

标签: pandas

我有两个pd df,我想根据df1中的ID将df2合并到df1的每一行。最终的df应该看起来像df3中的一样。

我该怎么做?我尝试了合并,联接和合并,但并没有想要我想要的东西。

    df1

      ID  Division 
      1     10
      2      2 
      3      4   
      ...  ...


   df2 

     Product type  Level 
       1            0
       1            1 
       1            2
       2            0
       2            1
       2            2
       2            3 


     df3
       ID   Product type Level    Division
       1      1            0          10
       1      1            1          10
       1      1            2          10
       1      2            0          10
       1      2            1          10
       1      2            2          10
       1      2            3          10
       and repeat for ID 2 and ......

2 个答案:

答案 0 :(得分:1)

看起来您正在寻找两个数据框的笛卡尔积。以下方法应该可以实现您想要的,

(df1.assign(key=1)
    .merge(df2.assign(key=1))
    .drop('key', axis=1))

答案 1 :(得分:0)

考虑这样的选项:

  • 将两个DataFrame中的索引都设置为 0
  • 执行外部联接(在索引上,因此结果只是笛卡尔坐标 产品),
  • 重置索引。

执行此操作的代码是:

df1.index = [0] * df1.index.size
df2.index = [0] * df2.index.size
result = df1.join(df2, how='outer').reset_index(drop=True)