Pandas Specific Pivot of DataFrame

Question:

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.

Asked By: Dominique Garmier

||

Answers:

Please find your answer in pandas documentation
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html

Answered By: Ashutosh

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
Answered By: Naveed
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.