2
votes

I have two dataframes df1 and df2 I want to join. Their indexes are not the same and they don't have any common columns. What I want is to join them based on the order of the rows, i.e. join the first row of df1 with the first row of df2, the second row of df1 with the second row of df2, etc.

Example:

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

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

Should give

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

I don't care about the indexes in the final dataframe. I tried reindexing df1 with the indexes of df2 but could not make it work.

3

3 Answers

2
votes

You could assign to df1 index of df2 and then use 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

Or you could do it in one line with 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
votes

Try concat:

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

The reset_index() calls make the indices the same, then, concat with axis=1 simply joins horizontally.

1
votes

I guess you can try to join them (doing this it performs the join on the index, which is the same for the two DataFrame due to reset_index):

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