0

I am trying to reshape a given DataFrame

   ts type  value1  value2
0   1  foo      10      16
1   1  bar      11      17
2   2  foo      12      18
3   2  bar      13      19
4   3  foo      14      20
5   3  bar      15      21

into the following shape:

     foo           bar
  value1 value2 value1 value2
1     10     16     11     17
2     12     18     13     19
3     14     20     15     21

I know how to do this programatically, this is not the point. But I for the life of me can't find the proper pandas method to do this efficiently.

Help would be greatly appreciated.

1 Answers1

1

here is one way to do it

df.set_index(['type','ts']).unstack(0).swaplevel(axis=1).sort_index(axis=1)
type    bar     foo
    value1  value2  value1  value2
ts              
1   11  17  10  16
2   13  19  12  18
3   15  21  14  20
Naveed
  • 11,495
  • 2
  • 14
  • 21
  • thanks for the quick answer! the `swaplevel(...).sort_index(...)` part was what I was missing. Using that I found a perhaps slightly shorter version: `df.pivot(index='ts', columns='type').swaplevel(axis=1).sort_index(axis=1)` – Dominique Garmier Nov 16 '22 at 20:41
  • yes. Pivot is another way to go about it. – Naveed Nov 16 '22 at 20:41