数据框:-
ID spend month_diff
12 10 -1
12 10 -2
12 20 1
12 30 2
13 15 -1
13 20 -2
13 25 1
13 30 2
我想根据特定ID的月份差额获得month_diff的负数表示客户去年的支出,而正数表示今年。所以,我想比较过去一年和今年的客户支出。因此条件如下:
条件:-
if month_diff >= -2 and < 0 then cumulative spend for negative months - flag=pre
if month_diff > 0 and <=2 then cumulative spend for positive months - flag=post
所需数据帧:-
ID spend month_diff tot_spend flag
12 10 -2 20 pre
12 30 2 50 post
13 20 -2 35 pre
13 30 2 55 post
将numpy.sign
,numpy.sign
和Series.shift
与Series.shift
用于连续的组,并以合计Series.ne
和Series.ne
传递到Series.cumsum
。
最后使用Series.cumsum
:
DataFrame.groupby