Skip to content

Tag: datetimeindex

Datetime rolling count per category in Pandas

Starting from a DataFrame with a date and user column, I’d like to add a third count_past_5_days column to indicate the rolling count of occurrences of each row’s user during the past 5 days: date user count_past_5_days 2020-01-01 abc 1 2020-01-01 def 1 2020-01-02 abc 2 2020-01-03 abc 3 2020-01-04 abc 4 2020-01-04 def 2 2020-01-04 ghi 1 2020-01-05 abc

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