numpy - Unpivot Pandas Data -
i have dataframe
laid out as:
jan feb mar apr ... 2001 1 12 12 19 2002 9 ... 2003 ...
and "unpivot" data like:
date value jan 2001 1 feb 2001 1 mar 2001 12 ... jan 2002 9
what best way accomplish using pandas/ numpy?
you have df.unstack()
, create multiindexed series month first level , year second level index. if want them columns 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
Comments
Post a Comment