I want to keep the rows that recharged(recharge_number) more than 2 times from a single recharge number in the last 3 months(month_n = 4 to 6). Assume the current month is 7. If any recharge number meets that condition then keep all the information associated with that number.
account_no recharge_number year month_n
52 1300002 2021 6
52 1300002 2021 5
52 1300002 2021 4
52 1300002 2021 1
52 1644460 2021 6
52 1644460 2021 5
52 1644460 2021 2
70 1553984 2020 12
70 1553984 2020 11
91 1915689 2021 6
91 1915689 2021 5
91 1915689 2021 4
91 1915689 2020 12
91 1915689 2020 11
91 1915689 2020 10
52 1300002 2020 9
output:
account_no recharge_number year month_n
52 1300002 2021 6
52 1300002 2021 5
52 1300002 2021 4
91 1915689 2021 6
91 1915689 2021 5
91 1915689 2021 4
i tried this by the following code. Is this the right way or Is there any better solution?
df = df.groupby(['account_no','recharge_number','year','month']).recharge_number.agg('count').to_frame('recharge_count').reset_index()
df[((df.month_n >=4) & (df.year ==2021) & (df.recharge_count>=3))]