将DatetimeIndex拆分为Pandas中的日期和时间MultiIndex

时间:2014-05-08 18:39:56

标签: python pandas timestamp time-series multi-index

所以,让我们说我有DatetimeIndex:ed这样的数据(当然会有几天):

                             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

我想要像这样的MultiIndexed:

                                 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

我知道你可以(可能)提取DatetimeIndex,将它与.date()和.time()分成两列并将其设置为Dataframe的新索引,但还有更多&# 39; pandaic'这样做的方式?在我看来,这种功能会派上用场......

1 个答案:

答案 0 :(得分:9)

我能想到的最佳方式是

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]