Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas Specific Pivot of DataFrame

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Help would be greatly appreciated.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading