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