I have a DataFrame with dates as second level index. How can I filter between two dates?
Here is the code to generate the DataFrame:
dates=pd.date_range(start='2015-01-01', end='2018-12-01', freq='M')
persons=['John','Paul','Susan','Steve','Anne','Carol']
miindex=pd.MultiIndex.from_product([persons, dates],
names=['persons', 'dates'])
df = pd.DataFrame(np.random.randn(282, 4), columns=list('ABCD'), index=miindex)
A B C D
persons dates
John 2015-01-31 -1.381854 0.438590 -1.838329 0.085944
2015-02-28 -1.870273 0.040513 1.116906 0.473218
2015-03-31 0.522960 -0.190412 -0.650339 -0.532672
2015-04-30 0.147605 -0.045129 1.209839 1.831272
2015-05-31 -0.331290 -0.413971 -2.418138 0.149583
... ... ... ... ... ...
Carol 2018-07-31 -0.344657 0.871752 -0.040436 0.132283
2018-08-31 0.168781 0.776657 -0.103212 -0.082286
2018-09-30 0.019738 0.151568 -0.794741 -1.316847
2018-10-31 -1.047699 0.913352 1.009840 0.070882
2018-11-30 -1.360346 -0.850818 -0.824563 0.305373
How could I filter rows with following dates:
- included in 2016
- between 2015 and 2017
- from 01-02-2016 and on
- from 01-01-2018 and on
For example, filtering for dates from 01-01-2018 and on I should get
A B C D
persons dates
John 2018-01-31 1.092697 -0.534817 1.498770 -0.746335
2018-02-28 0.141443 0.286186 -0.652946 -0.331205
2018-03-31 -0.547728 0.942533 -0.315792 -1.564275
2018-04-30 2.383790 1.117817 -0.419611 1.603313
2018-05-31 0.405304 -1.468452 -0.713453 0.605490
... ... ... ...
Carol 2018-07-31 0.711990 0.615596 1.198836 2.283507
2018-08-31 -0.071486 -0.102290 -1.855148 0.284160
2018-09-30 1.461128 -1.163214 1.142434 0.183197
2018-10-31 -1.994097 -0.275098 0.877738 -1.094145
2018-11-30 0.225581 2.194110 0.160663 1.582566
Notice that you must ignore the value at columns A, B, C, D in my output because I generated the DataFrame randomly only with the indexes expected to show the content.