Skip to content
Advertisement

How to filter a pandas series with a datetime index on the quarter and year

I have a Series, called ‘scores’, with a datetime index.

I wish to subset it by quarter and year
pseudocode: series.loc['q2 of 2013']

Attempts so far:
s.dt.quarter

AttributeError: Can only use .dt accessor with datetimelike values

s.index.dt.quarter

AttributeError: ‘DatetimeIndex’ object has no attribute ‘dt’

This works (inspired by this answer), but I can’t believe it is the right way to do this in Pandas:

d = pd.DataFrame(s)
d['date'] = pd.to_datetime(d.index)
d.loc[(d['date'].dt.quarter == 2) & (d['date'].dt.year == 2013)]['scores']

I expect there is a way to do this without transforming into a dataset, forcing the index into datetime, and then getting a Series from it.

What am I missing, and what is the elegant way to do this on a Pandas series?

Advertisement

Answer

JavaScript

If you don’t want to create a new Series that holds a label for each quarter (e.g., if you are subsetting just once), you could even do

JavaScript
Advertisement