Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a dataframe to the right of another one with the same columns

I have two different dataframes with the same column names:

eg.

     0   1   2
0   10  13  17
1   14  21  34
2   68  32  12

     0   1   2 
0   45  56  32
1    9  22  86
2   55  64  19

I would like to append the second frame to the right of the first one while continuing the column names from the first frame. The output would look like this:

    0   1   2   3   4   5
0  10  13  17  45  56  32
1  14  21  34   9  22  86
2  68  32  12  55  64  19

What is the most efficient way of doing this? Thanks.

like image 460
Zito Relova Avatar asked Oct 19 '25 10:10

Zito Relova


2 Answers

Use pd.concat first and then reset the columns.

In [1108]: df_out = pd.concat([df1, df2], axis=1)

In [1109]: df_out.columns = list(range(len(df_out.columns)))

In [1110]: df_out
Out[1110]: 
    0   1   2   3   4   5
0  10  13  17  45  56  32
1  14  21  34   9  22  86
2  68  32  12  55  64  19
like image 147
cs95 Avatar answered Oct 21 '25 23:10

cs95


Why not join:

>>> df=df.join(df_,lsuffix='_')
>>> df.columns=range(len(df.columns))
>>> df
    0   1   2   3   4   5
0  10  13  17  45  56  32
1  14  21  34   9  22  86
2  68  32  12  55  64  19
>>> 

join is your friend, i use lsuffix (could be rsuffix too) to ignore error for saying duplicate columns.

like image 43
U12-Forward Avatar answered Oct 22 '25 00:10

U12-Forward