Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rolling Unique Sum for 3 previous months in python

The following is the dataset I am looking at.

Input:-
Date          Name
01/01/2017    A
01/03/2017    B
02/05/2017    A
03/17/2017    C
04/08/2017    D
05/10/2017    B
06/12/2017    D

Output:-
Date      Unique Count
Jan 2017    2
Feb 2017    2
Mar 2017    3
Apr 2017    3
May 2017    3
Jun 2017    2

I want to get unique counts of "Name" in previous 3 months on rolling basis. For example for date 06/12/2017 the previous 3 months including itself is april, May, June. So April had "D", May had "B" and June had "D". So the unique count of June Month is 2. Similarly for all the other months as well.

I am looking for a pandas function that could help me achieve this. Or any custom code that could implement this.

Any help is appreciated.

like image 546
howard roark Avatar asked Jul 16 '26 15:07

howard roark


1 Answers

Try:

months = pd.to_datetime(d.loc[:, "Date"]).dt.to_period("M")
out = pd.DataFrame([
    (month, len(d.loc[(-2 <= months - month) & (months - month <= 0), "Name"].unique()))
    for month in months.unique()])
like image 152
Kodiologist Avatar answered Jul 18 '26 04:07

Kodiologist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!