2017-10-17 252 views
2

我有這樣一個數據幀的累積總和鹼:復位條件熊貓

customer spend hurdle 
A   20 50  
A   31 50  
A   20 50  
B   50 100  
B   51 100  
B   30 100  

我要計算附加列的累積,這將在相同的客戶復位基地當累積總和大於或等於所述障礙像下面:

customer spend hurdle Cumulative 
A   20 50  20 
A   31 50  51 
A   20 50  20 
B   50 100  50 
B   51 100 101 
B   30 100  30 

我用cumsumgroupby的大熊貓,但我不知道如何將其底座上的狀態復位。

以下是我目前正在使用的代碼:

df1['cum_sum'] = df1.groupby(['customer'])['spend'].apply(lambda x: x.cumsum()) 

我知道這只是一個正常的累計總和。我非常感謝你的幫助。

回答

1

一種方法是下面的代碼。但這是一個非常低效和不雅的單線。

df1.groupby('customer').apply(lambda x: (x['spend'].cumsum() *(x['spend'].cumsum() > x['hurdle']).astype(int).shift(-1)).fillna(x['spend'])) 
+0

我在你的電腦上添加了一個改進版本。 – Zero

1

可能有更快,更有效的方法。這是一種效率低下的方式。

In [3270]: def custcum(x): 
     ...:  total = 0 
     ...:  for i, v in x.iterrows(): 
     ...:   total += v.spend 
     ...:   x.loc[i, 'cum'] = total 
     ...:   if total >= v.hurdle: 
     ...:   total = 0 
     ...:  return x 
     ...: 

In [3271]: df.groupby('customer').apply(custcum) 
Out[3271]: 
    customer spend hurdle cum 
0  A  20  50 20.0 
1  A  31  50 51.0 
2  A  20  50 20.0 
3  B  50  100 50.0 
4  B  51  100 101.0 
5  B  30  100 30.0 

您可以考慮使用cythonnumba加快custcum


[更新]​​答案

改進版本。

In [3276]: s = df.groupby('customer').spend.cumsum() 

In [3277]: np.where(s > df.hurdle.shift(-1), s, df.spend) 
Out[3277]: array([ 20, 51, 20, 50, 101, 30], dtype=int64)