Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataframe pivot in specific format

Currently I have a dataframe in the following format :

ID  Value   Type    Month
1   0.1     B       Jan
2   0.2     A       Jan
1   0.15    A       Feb
2   0.1     B       Feb

I am trying to get it to display each column value by month like so:

Month Jan            Feb
      Value   Type   Value   Type
ID     
1     0.1     B      0.15    A
2     0.2     A      0.1     B

I run the following to pivot the data

df.pivot(index='ID', columns='Month', values=['Type', 'Value'])

But instead the table comes out like so

      Value        Type
      Jan   Feb    Jan   Feb
ID     
1     0.1   0.15   B     A
2     0.2   0.1    A     B

Is there any way to get it to come out like I want? Have not been able to find a way to structure the pivot table like I want to. How to pivot a dataframe does not appear to address this specific format request

like image 612
phill2424 Avatar asked Dec 06 '25 19:12

phill2424


1 Answers

Use swaplevel and sort_index from your last pivotted df.

df2.swaplevel(axis=1).sort_index(axis=1, ascending=[False, False])

Month   Jan        Feb     
      Value Type Value Type
ID                         
1       0.1    B  0.15    A
2       0.2    A   0.1    B
like image 93
rafaelc Avatar answered Dec 08 '25 09:12

rafaelc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!