Skip to main content
 首页 » 编程设计

python之使用 MultiIndex with Time 进行子集化

2024年10月01日7jpfss

我是 pandas 中的 MultiIndex 的新手,但在某些情况下它会有所帮助。我有一个带有 MultiIndex(ON_SCENE 和 LAST)的 df,结构如下:

                              ID                 
ON_SCENE            LAST                                                     
2016-05-05 03:58:54 last1    1000             
2016-05-05 17:23:39 last1    1001              
2016-05-05 18:20:50 last1    1002              
2016-05-05 21:30:29 last2    1003            
2016-05-05 22:33:19 last2    1004   
2016-05-05 23:30:23 last3    1005 
2016-05-06 00:08:34 last3    1006 
2016-05-06 01:33:54 last3    1007 

我想像这样使用日期和姓氏对这些数据进行子集化:

df.loc[j.strftime('%Y-%m-%d'),Last_Name] 

其中 j 是 datetime.date 类型,Last_Name 是具有姓氏的 str。不幸的是,我不断收到 KeyError。我也试过:

    df[j.strftime('%Y-%m-%d')] 
    df[Last_Name] 

但是这些也给我一个KeyErrors。不确定我做错了什么?

请您参考如下方法:

In [103]: x.loc[('2016-05-05', 'last2'), :] 
Out[103]: 
                             ID 
ON_SCENE            LAST 
2016-05-05 21:30:29 last2  1003 
2016-05-05 22:33:19 last2  1004 

或使用 pd.IndexSlice:

In [104]: idx = pd.IndexSlice 
 
In [105]: x.loc[idx['2016-05-05':'2016-05-06', 'last3'], :] 
Out[105]: 
                             ID 
ON_SCENE            LAST 
2016-05-05 23:30:23 last3  1005 
2016-05-06 00:08:34 last3  1006 
2016-05-06 01:33:54 last3  1007 

Pandas Documentation with examples