Pandas: Convert PeriodIndex to Multiindex (Year, Month)

Viewed 170

I have a dataframe with a few time series of measurement taken every hour. After some elaboration and grouping by month, the index is:

PeriodIndex(['2015-01', '2015-02', '2015-03', '2015-04', '2015-05', '2015-06',
         '2015-07', '2015-08', '2015-09', '2015-10', '2015-11', '2015-12',
         '2016-01', '2016-02', '2016-03', '2016-04', '2016-05', '2016-06',
         '2016-07', '2016-08', '2016-09', '2016-10', '2016-11', '2016-12'],
        dtype='period[M]', name='DT', freq='M')

I would like (and it'd help a lot) to convert this into a multiindex with the years as first level and months as the second.

How can I do it?

1 Answers

Use MultiIndex.from_arrays with PeriodIndex.year and PeriodIndex.month:

idx = pd.PeriodIndex(['2015-01', '2015-02', '2015-03', '2015-04', '2015-05', '2015-06',
         '2015-07', '2015-08', '2015-09', '2015-10', '2015-11', '2015-12',
         '2016-01', '2016-02', '2016-03', '2016-04', '2016-05', '2016-06',
         '2016-07', '2016-08', '2016-09', '2016-10', '2016-11', '2016-12'],
        dtype='period[M]', name='DT', freq='M')

mux = pd.MultiIndex.from_arrays([idx.year, idx.month], names=['year','month'])
print (mux)
MultiIndex(levels=[[2015, 2016], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
           labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
                    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
                    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]],
           names=['year', 'month'])
Related