0

I have data in the following structure in pandas dataframe

User    day games_won   games_draw  games_lost  tips_taken
user1   1   10               4          2         5
user2   1   16               7          1         3
user1   2   2                8          7         0

And I want it to be converted into the following format

User    day games_won_day1  games_won_day2  games_draw_day1  games_draw_day2  games_lost_day1   games _lost_day2  tips_taken_day1 tips_taken_day2
cs95
  • 379,657
  • 97
  • 704
  • 746
Ravi Kiran
  • 11
  • 2

1 Answers1

0

You can start by setting the index, then unstacking. Finally, fix the headers.

df2 = df.set_index(['User', 'day']).unstack()
df2.columns = df2.columns.map('{0[0]}_day{0[1]}'.format)

df2

       games_won_day1  games_won_day2  games_draw_day1  games_draw_day2  games_lost_day1  games_lost_day2  tips_taken_day1  tips_taken_day2
User                                                                                                                                       
user1            10.0             2.0              4.0              8.0              2.0              7.0              5.0              0.0
user2            16.0             NaN              7.0              NaN              1.0              NaN              3.0              NaN

If you don't want "User" as the index in the output, you can reset it after. I think it makes sense to keep, however.

cs95
  • 379,657
  • 97
  • 704
  • 746