Skip to content Skip to sidebar Skip to footer

Pandas Reindex Multiindex And Shift Values By Second Index

I have a pandas DataFrame looking like this : x1 x2 x3 x4 Date Time

Solution 1:

The fastest way I can think of is to overwrite the entire first level (innermost level) of the MultiIndex with a 20-minute-shifted version of itself:

x.index = x.index.set_levels(x.index.levels[1].shift(20, 'min'), level=1)

Example

x = pd.DataFrame(index=pd.MultiIndex.from_product([pd.date_range('2017-01-03', '2017-01-06', freq='1D'), 
                                                   pd.date_range('09:00', '17:00', freq='20min')]))
x.loc[:, 'x1'] = list(range(len(x)))

x
                                x1
2017-01-03 2018-06-14 09:00:00   0
           2018-06-14 09:20:00   1
           2018-06-14 09:40:00   2
           2018-06-14 10:00:00   3
           2018-06-14 10:20:00   4
    ...                         ..
2017-01-06 2018-06-14 15:40:00  95
           2018-06-14 16:00:00  96
           2018-06-14 16:20:00  97
           2018-06-14 16:40:00  98
           2018-06-14 17:00:00  99

x.index = x.index.set_levels(x.index.levels[1].shift(20, 'min'), level=1)

x
                                x1
2017-01-03 2018-06-14 09:20:00   0
           2018-06-14 09:40:00   1
           2018-06-14 10:00:00   2
           2018-06-14 10:20:00   3
           2018-06-14 10:40:00   4
    ...                         ..
2017-01-06 2018-06-14 16:00:00  95
           2018-06-14 16:20:00  96
           2018-06-14 16:40:00  97
           2018-06-14 17:00:00  98
           2018-06-14 17:20:00  99

Post a Comment for "Pandas Reindex Multiindex And Shift Values By Second Index"