python - 使用 MultiIndex 和 Time 进行子集化

标签 python pandas datetime multi-index data-munging

我是 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

关于python - 使用 MultiIndex 和 Time 进行子集化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44396277/

相关文章:

python - Pandas :在数据框中重新分配值

sql - PostgreSQL 比较两个 timestamptz

MySQL 选择日期时间之间

python - 如何使用 Pandas 以更优化的方式将字符串值转换为-int值

python - 将库存位置与产品型号相关联 - OpenERP 报告

python - 将 CSV 从 Azure Data Lake Storage Gen 2 读取到 Pandas Dataframe |无数据库

python - 更快的 strptime?

python - 教程中出现多个 SparkContexts 错误

python - Latex 与 IPython (IPython) 错误

python - 如何在 DataFrame 中存储 DataFrame