Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time slice on second level of multiindex

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
like image 592
Brian Avatar asked Jul 13 '16 08:07

Brian


People also ask

How do you slice in MultiIndex?

Using slicers You can slice a MultiIndex by providing multiple indexers. You can provide any of the selectors as if you are indexing by label, see Selection by Label, including slices, lists of labels, labels, and boolean indexers. You can use slice(None) to select all the contents of that level.

What does the pandas function MultiIndex From_tuples do?

from_tuples() function is used to convert list of tuples to MultiIndex. It is one of the several ways in which we construct a MultiIndex.


1 Answers

Use pd.IndexSlice

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

enter image description here

like image 194
piRSquared Avatar answered Sep 25 '22 23:09

piRSquared