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
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.
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.
Use pd.IndexSlice
df.loc[pd.IndexSlice[:, '2001-01':'2001-3'], :]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With