Reputation: 646
I have the following dataframe. I need to group by ID adding the PROFIT column based on the last 30 and 60 days.
import pandas as pd
df = pd.DataFrame({"ID":[1,1,1,1,2,2,2,2],"DATE":['2019-04-03','2019-03-03','2019-03-01','2019-02-03','2019-02-01','2019-01-01','2019-01-06','2019-04-03'],"PROFIT":[10,20,30,60,90,100,20,10]})
ID DATE PROFIT
0 1 2019-04-03 10
1 1 2019-03-03 20
2 1 2019-03-01 30
3 1 2019-02-03 60
4 2 2019-02-01 90
5 2 2019-01-01 100
6 2 2019-01-06 20
7 2 2019-04-03 10
Final Result:
df_end = pd.DataFrame({"ID":[1,1,2,2],"TIME":[30,60,30,60],"SUM_PROFIT":[10,60,10,90]})
ID TIME SUM_PROFIT
0 1 30 10
1 1 60 60
2 2 30 10
3 2 60 90
Upvotes: 0
Views: 86
Reputation: 153460
IIUC, then you can try something like this:
timespan = [30, 60]
pd.concat([df.sort_values('DATE', ascending=False)
.groupby(['ID'])
.apply(lambda x: x.loc[x['DATE'].head(1).values[0]-x['DATE']<=pd.Timedelta(days=t),'PROFIT'].sum())
.rename('SUM_PROFIT').reset_index().assign(TIME = t) for t in timespan],
ignore_index=True)
Output:
ID SUM_PROFIT TIME
0 1 10 30
1 2 10 30
2 1 120 60
3 2 10 60
Upvotes: 1