Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split DatetimeIndex into date and time MultiIndex conveniently in Pandas

So let's say I have DatetimeIndex:ed data like this (there would be several days of course):

                             X      Y       Z
timestamp           
2013-01-02 10:00:13.295000   366    -8242   -1820
2013-01-02 10:00:13.329000   366    -8016   -1820
2013-01-02 10:00:13.352000   32     -8016   -1820
2013-01-02 10:00:13.882000   32     -9250   -1820
2013-01-02 10:00:15.076000  -302    -9250   -1820

and I want it MultiIndexed like this:

                                 X      Y       Z
Date           Time     
2013-01-02     10:00:13.295000   366    -8242   -1820
               10:00:13.329000   366    -8016   -1820
               10:00:13.352000   32     -8016   -1820
               10:00:13.882000   32     -9250   -1820
               10:00:15.076000  -302    -9250   -1820

I know you could (probably) extract the DatetimeIndex, split it with .date() and .time() into two columns and set it as a new index for the Dataframe, but is there a more 'pandaic' way of doing this? It would seem to me that this sort of functionality would come handy...

like image 882
H. Arponen Avatar asked May 08 '14 18:05

H. Arponen


People also ask

How convert MultiIndex to columns in pandas?

pandas MultiIndex to ColumnsUse pandas DataFrame. reset_index() function to convert/transfer MultiIndex (multi-level index) indexes to columns. The default setting for the parameter is drop=False which will keep the index values as columns and set the new index to DataFrame starting from zero.


1 Answers

The best way I can think of is

In [13]: df.index = pd.MultiIndex.from_arrays([df.index.date, df.index.time], names=['Date','Time'])

In [14]: df
Out[14]: 
                              X     Y     Z
Date       Time                            
2013-01-02 10:00:13.295000  366 -8242 -1820
           10:00:13.329000  366 -8016 -1820
           10:00:13.352000   32 -8016 -1820
           10:00:13.882000   32 -9250 -1820
           10:00:15.076000 -302 -9250 -1820

[5 rows x 3 columns]
like image 66
Happy001 Avatar answered Sep 28 '22 04:09

Happy001