我有以下数据帧。我需要根据最近30天和60天的ID添加PROFIT列进行分组。
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
最后结果:
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
IIUC,然后你可以尝试这样的事情:
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)
输出:
ID SUM_PROFIT TIME
0 1 10 30
1 2 10 30
2 1 120 60
3 2 10 60