根据行顺序加入两个pandas数据帧

时间:2016-02-07 19:07:54

标签: join pandas concatenation

我想要加入两个数据帧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,但无法使其正常工作。

3 个答案:

答案 0 :(得分:2)

您可以指定df1的{​​{1}}索引,然后使用df2

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

答案 1 :(得分:2)

尝试concat

print [i for i in reversed(l)]

pd.concat([df1.reset_index(), df2.reset_index()], axis=1) ()调用使索引相同,然后reset_index concat只是水平连接。

答案 2 :(得分:1)

我猜你可以尝试加入它们(这样做会在索引上执行连接,这对于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