In Python Pandas is there a way multiple rows next to each other on one row? keeping the order

Viewed 132
current 

name Mon Tues 
sony 5    5   
sony 4    6
coby 1    8
coby 2    7

Desired

name Mon Tues Mon Tues
sony 5    5   4    6
coby 1    8   2    7

I have tried to use .melt but it just stacks on top so it goes Mon,Mon,Tues,Tues not Mon,Tues,Mon,Tues.

Thank you

1 Answers

This is essentially pivot with one column. You can sort the index after pivot, in this case, by level=(1,0):

(df.assign(col=df.groupby('name').cumcount())
   .pivot(index='name', columns='col').T
   .sort_index(level=(1,0))
   .reset_index(level=1,drop=True)
   .T.reset_index()
)

Output:

   name  Mon  Tues  Mon  Tues
0  coby    1     8    2     7
1  sony    5     5    4     6
Related