首页 > 解决方案 > Python中的条件滚动总和

问题描述

我正在从 Excel 中的数据分析过渡到 Python,并且无法找到 Python 中的等效代码在我的数据框中使用的解决方案。要计算 Rolling Sum 列,我将使用公式 IF(C3=FALSE,0,(1+D2)) (对于下面发布的表格)。在本例中,只要 > 20 列中的 Amount 值大于 20,则返回 1 的值,然后将其添加到其上方的金额中。

我尝试在 Python 中创建 Rolling Sum 列:

def f(row):
     if row['> 20'] == False:
          val = 0

     else:
          #getting stuck here as to how to add to the row above, shift(1) is incorrect
          val = 1 + shift(1)
     return val

df['Rolling Sum'] = df.apply(f, axis=1)





Event | Amount | > 20  | Rolling Sum |
+-------+--------+-------+-------------+
|     1 |      7 | FALSE |             |
|     2 |     25 | TRUE  |           1 |
|     3 |     28 | TRUE  |           2 |
|     4 |      3 | FALSE |           0 |
|     5 |     30 | TRUE  |           1 |
|     6 |     35 | TRUE  |           2 |
|     7 |     40 | TRUE  |           3 |
|     8 |      6 | FALSE |           0 |
+-------+--------+-------+-------------+

标签: python

解决方案


用 iterrows 试试这个:

for index, row in df.iterrows():
    if df.loc[index, '> 20'] == True:
        df.loc[index, 'Rolling Sum'] = df.loc[index-1, 'Rolling Sum']+1
    else:
        df.loc[index, 'Rolling Sum'] = 0

推荐阅读