2

I have a dataframe that looks as following:

Type Month  Value
A    1      0.29
A    2      0.90
A    3      0.44
A    4      0.43
B    1      0.29
B    2      0.50
B    3      0.14
B    4      0.07

I want to change the dataframe to following format:

Type    A      B
1      0.29    0.29
2      0.90    0.50
3      0.44    0.14
4      0.43    0.07

Is this possible ?

MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
Zanam
  • 4,607
  • 13
  • 67
  • 143
  • Possible duplicate of [Pandas long to wide reshape](http://stackoverflow.com/questions/22798934/pandas-long-to-wide-reshape) – Laurent Mar 28 '17 at 22:03

3 Answers3

3

Use set_index + unstack

df.set_index(['Month', 'Type']).Value.unstack()

Type      A     B
Month            
1      0.29  0.29
2      0.90  0.50
3      0.44  0.14
4      0.43  0.07

To match your exact output

df.set_index(['Month', 'Type']).Value.unstack().rename_axis(None)

Type      A     B
1      0.29  0.29
2      0.90  0.50
3      0.44  0.14
4      0.43  0.07
piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • 2
    df.set_index(['Month','Type']).squeeze().unstack().rename_axis(None) if you are to lazy to remember the name of that pesky "Value" column. A trick @TedPetrou showed me. – Scott Boston Mar 28 '17 at 20:11
  • @ScottBoston I'm not perfect, but I try to provide solutions that are generalizable, or is obvious how to generalize (I'm certain you can find posts of mine where this isn't `True`). IMO `squeeze` obscures what is happening **and** if by chance the dataframe had another column, it would not work as intended. – piRSquared Mar 28 '17 at 20:17
  • Point taken. Thanks. – Scott Boston Mar 28 '17 at 20:21
3

Pivot solution:

In [70]: df.pivot(index='Month', columns='Type', values='Value')
Out[70]:
Type      A     B
Month
1      0.29  0.29
2      0.90  0.50
3      0.44  0.14
4      0.43  0.07

In [71]: df.pivot(index='Month', columns='Type', values='Value').rename_axis(None)
Out[71]:
Type     A     B
1     0.29  0.29
2     0.90  0.50
3     0.44  0.14
4     0.43  0.07
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
0

You're having a case of long format table which you want to transform to a wide format.

This is natively handled in pandas:

df.pivot(index='Month', columns='Type', values='Value')
Laurent
  • 1,914
  • 2
  • 11
  • 25