1

I want to reshape a pandas dataframe from this:

id1 id2 id3 variable value
x    y  z   var_a        1
x    y  z   var_b        2
x    y  z   var_c        3
x    y  z   var_d        4
x2   y2 z2  var_a        5
x2   y2 z2  var_b        6
x2   y2 z2  var_c        7
x2   y2 z2  var_d        8

into this:

id1 id2 id3 var_a var_b var_c var_d
x   y   z   1     2     3     4
x2  y2  z2  5     6     7     8

How do I do this in pandas?

F. Doyle
  • 13
  • 3

1 Answers1

1

pandas' equivalent of R's cast is pivot_table:

>>> df.pivot_table(index=['id1','id2','id3'], columns=['variable'], values=['value'])
            value                  
variable    var_a var_b var_c var_d
id1 id2 id3                        
x   y   z       1     2     3     4
x2  y2  z2      5     6     7     8
smci
  • 32,567
  • 20
  • 113
  • 146