ben121 ben121 - 2 months ago 11
Python Question

Pandas Filter on date for quarterly ends

In the index column I have a list of dates:

DatetimeIndex(['2010-12-31', '2011-01-02', '2011-01-03', '2011-01-29',
'2011-02-26', '2011-02-28', '2011-03-26', '2011-03-31',
'2011-04-01', '2011-04-03',
...
'2016-02-27', '2016-02-29', '2016-03-26', '2016-03-31',
'2016-04-01', '2016-04-03', '2016-04-30', '2016-05-31',
'2016-06-30', '2016-07-02'],
dtype='datetime64[ns]', length=123, freq=None)


However I want to filter out all those which the month and day equal to 12/31, 3/31, 6/30, 9/30 to get the value at the end of the quarter.

Is there a good way of going about this?

Answer

You can use is_quarter_end to filter the row labels:

In [151]:
df = pd.DataFrame(np.random.randn(400,1), index= pd.date_range(start=dt.datetime(2016,1,1), periods=400))
df.loc[df.index.is_quarter_end]

Out[151]:
                   0
2016-03-31 -0.474125
2016-06-30  0.931780
2016-09-30 -0.281271
2016-12-31  0.325521