Home > Net >  Pandas join rows as new columns
Pandas join rows as new columns

Time:11-25

I have the following df:

import pandas as pd
df = pd.DataFrame({'C':[5,4],'P':[2.3,5.6]})

enter image description here

I would like to join row 1 to row 0 as follows:

enter image description here

I understand that duplicate columns get assigned a "_1".

CodePudding user response:

Your actual use case may be more complex but for your simple example, you can do the following.

Option 1 - use unstack()

df.unstack().reset_index().drop('level_1', axis=1).set_index('level_0').T

level_0    C    C    P    P
0        5.0  4.0  2.3  5.6

Option 2 - use concat()

pd.concat([df.iloc[0], df.iloc[1]], axis=0).to_frame().T

     C    P    C    P
0  5.0  2.3  4.0  5.6

Option 3 - use merge()

(df.iloc[0].to_frame().T.reset_index(drop=True)).merge((df.iloc[1].to_frame().T.reset_index(drop=True)), left_index=True, right_index=True)

   C_x  P_x  C_y  P_y
0  5.0  2.3  4.0  5.6

Option 4 - use numpy.reshape()

pd.DataFrame(np.reshape(df.to_numpy(),(1,-1)))

     0    1    2    3
0  5.0  2.3  4.0  5.6
  • Related