Unpivot Pandas Data

dataframe, numpy, pandas, python

Solution

You just have to do `df.unstack()` and that will create a MultiIndexed Series with month as a first level and the year as the second level index. If you want them to be columns then just call `reset_index()` after that.

>>> df
      Jan  Feb
2001    3    4
2002    2    7
>>> df.unstack()
Jan  2001    3
     2002    2
Feb  2001    4
     2002    7
>>> df = df.unstack().reset_index(name='value')
>>> df
  level_0  level_1  value
0     Jan     2001      3
1     Jan     2002      2
2     Feb     2001      4
3     Feb     2002      7
>>> df.rename(columns={'level_0': 'month', 'level_1': 'year'}, inplace=True)
>>> df
  month  year  value
0   Jan  2001      3
1   Jan  2002      2
2   Feb  2001      4
3   Feb  2002      7

Problem

I currently have a `DataFrame` laid out as: ``` Jan Feb Mar Apr ... 2001 1 12 12 19 2002 9 ... 2003 ... ``` and I would like to "unpivot" the data to look like: ``` Date Value Jan 2001 1 Feb 2001 1 Mar 2001 12 ... Jan 2002 9 ``` What is the best way to accomplish this using pandas/NumPy?

Original source