time slice on second level of multiindex

2019-04-09 07:56发布

pandas allows for cool slicing on time indexes. For example, I can slice a dataframe df for the months from Janurary 2012 to March 2012 by doing:

df['2012-01':'2012-03']

However, I have a dataframe df with a multiindex where the time index is the second level. It looks like:

                     A         B         C         D         E
a 2001-01-31  0.864841  0.789273  0.370031  0.448256  0.178515
  2001-02-28  0.991861  0.079215  0.900788  0.666178  0.693887
  2001-03-31  0.016674  0.855109  0.984115  0.436574  0.480339
  2001-04-30  0.120924  0.046013  0.659807  0.210534  0.694029
  2001-05-31  0.788149  0.296244  0.478201  0.845042  0.437814
b 2001-01-31  0.497646  0.349958  0.223227  0.812331  0.975012
  2001-02-28  0.542572  0.472267  0.276186  0.970909  0.138683
  2001-03-31  0.960813  0.666942  0.069349  0.282741  0.127992
  2001-04-30  0.491422  0.678742  0.048784  0.612312  0.713472
  2001-05-31  0.718721  0.504403  0.069047  0.253682  0.836386

I can still slice using the method above on any specific level by:

df.loc['a']['2012-01':'2012-03']

But this is only for level0 == 'a'.

How do I do this for all values in level0? I expect something like this:

                     A         B         C         D         E
a 2001-01-31  0.864841  0.789273  0.370031  0.448256  0.178515
  2001-02-28  0.991861  0.079215  0.900788  0.666178  0.693887
  2001-03-31  0.016674  0.855109  0.984115  0.436574  0.480339
b 2001-01-31  0.497646  0.349958  0.223227  0.812331  0.975012
  2001-02-28  0.542572  0.472267  0.276186  0.970909  0.138683
  2001-03-31  0.960813  0.666942  0.069349  0.282741  0.127992

1条回答
来,给爷笑一个
2楼-- · 2019-04-09 08:08

Use pd.IndexSlice

df.loc[pd.IndexSlice[:, '2001-01':'2001-3'], :]

enter image description here

查看更多
登录 后发表回答