2

我是 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带有姓氏的 a。不幸的是,我不断收到 KeyError。我也试过:

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

但这些也给了我一个 KeyErrors。不知道我做错了什么?

4

1 回答 1

2
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 文档

于 2017-06-06T17:40:45.130 回答