0

My DataFrame looks like this:

  A   B   C   var     value   
0 1   1   1   alpha   34.15
1 1   1   1   beta    1916.95
2 1   1   1   gamma   83.64
3 1   1   1   delta   367.72
4 1   1   2   alpha   88.32
5 1   1   2   beta    2229.99
6 1   1   2   gamma   80.72
7 1   1   2   delta   498.68
8 1   1   3   alpha   39.49
9 1   1   3   beta    2831.05

My goal is to make alpha, beta, etc., into columns.

dt.unstack(var)

produces not a DataFrame object, but an array. Is there any way just to get a DataFrame object back, with alpha, beta, etc., being columns?

Anarcho-Chossid
  • 2,210
  • 4
  • 27
  • 44
  • Perhaps [this answer](http://stackoverflow.com/questions/22127569/opposite-of-melt-in-python-pandas#22127685) can help... – Primer Nov 19 '14 at 06:04
  • `unstack` works on the index, so you have to first set it as index: `dt.set_index('var').unstack()` – joris Nov 19 '14 at 08:00

1 Answers1

0

Try DataFrame.pivot, and you'll also have to decide what the index and values should be.

    dt.pivot('C', 'var', 'value')
var  alpha     beta   delta  gamma
C                                 
1    34.15  1916.95  367.72  83.64
2    88.32  2229.99  498.68  80.72
3    39.49  2831.05     NaN    NaN
A. Coady
  • 54,452
  • 8
  • 34
  • 40
  • ValueError: Index contains duplicate entries, cannot reshape. – Anarcho-Chossid Nov 21 '14 at 00:47
  • Yes, the choice of index column is crucial. In the example, 'C' doesn't have duplicate entries with respect to 'var', so it was the obvious choice. If there are duplicate entries, then it's ambiguous what to expect in the 'alpha', 'beta', ... columns. – A. Coady Dec 08 '14 at 21:20