【问题标题】:Join two pandas dataframes based on line order根据线序加入两个熊猫数据框
【发布时间】:2016-05-17 09:58:36
【问题描述】:

我有两个要加入的数据框 df1 和 df2。它们的索引不相同,并且它们没有任何公共列。我想要的是根据行的顺序加入它们,即将df1的第一行与df2的第一行,df1的第二行与df2的第二行等加入。

例子:

df1:
     'A'   'B'
  0   1     2
  1   3     4
  2   5     6 

df2:
     'C'   'D'
  0   7     8
  3   9     10
  5   11    12

应该给

     'A'    'B'   'C'   'D'
  0   1      2     7     8
  3   3      4     9     10
  5   5      6     11    12

我不关心最终数据帧中的索引。我尝试使用 df2 的索引重新索引 df1 但无法使其工作。

【问题讨论】:

    标签: join pandas concatenation


    【解决方案1】:

    您可以分配给df2df1 索引,然后使用join

    df1.index = df2.index
    res = df1.join(df2)
    
    In [86]: res
    Out[86]: 
       'A'  'B'  'C'  'D'
    0    1    2    7    8
    3    3    4    9   10
    5    5    6   11   12
    

    或者你可以在一行中使用set_index

    In [91]: df1.set_index(df2.index).join(df2)
    Out[91]: 
       'A'  'B'  'C'  'D'
    0    1    2    7    8
    3    3    4    9   10
    5    5    6   11   12
    

    【讨论】:

      【解决方案2】:

      试试concat:

      pd.concat([df1.reset_index(), df2.reset_index()], axis=1)
      

      reset_index() 调用使索引相同,然后,concataxis=1 只是水平连接。

      【讨论】:

      • 据我了解,OP 预计会获得带有 0 3 5 的索引,例如在 df2 中,而不是在 reset_index 之后获得的 0 1 2
      • 谢谢,但我认为这不是真的:“我不关心最终数据帧中的索引。”
      • 尽管如此,请对评论表示赞赏:-)
      • 是的,最终索引无关紧要。所有解决方案都有效,谢谢大家!
      • @AmiTavory 是的,错过了那部分文本(或者可能是多次编辑之一)。也赞成
      【解决方案3】:

      我猜你可以尝试加入它们(这样做会在索引上执行加入,由于reset_index,这对于两个 DataFrame 相同):

      In [18]: df1.join(df2.reset_index(drop=True))
      Out[18]: 
         'A'  'B'  'C'  'D'
      0    1    2    7    8
      1    3    4    9   10
      2    5    6   11   12
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 1970-01-01
        • 2017-11-30
        • 1970-01-01
        • 2019-01-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多