3

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

phill2424
  • 33
  • 2

1 Answers1

2

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
rafaelc
  • 57,686
  • 15
  • 58
  • 82