I always forget how to do this.
The pandas DataFrame.loc
method allows for label -based filtering of data
frames. The Pandas docs show how
it can be used to filter a MultiIndex
:
|
|
It turns out you can easily use it to filter a DateTimeIndex
level by a
single date with df['2016-11-07']
or a range of dates with
df['2016-11-07:2016-11-11']
. This applies whether or not its a MultiIndex
.
If you get an error like KeyError: 'Key length (1) was greater than MultiIndex lexsort depth (0)'
, it’s because “MultiIndex Slicing requires the
index to be fully lexsorted”. You may fix your problem by calling df = df.sort_index()
.