基于多个条件的细分总数

问题描述 投票:0回答:1

数据框:-

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
pandas dataframe segment
1个回答
0
投票

numpy.signnumpy.signSeries.shiftSeries.shift用于连续的组,并以合计Series.neSeries.ne传递到Series.cumsum

最后使用Series.cumsum

DataFrame.groupby
© www.soinside.com 2019 - 2024. All rights reserved.