python - 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 |
+-------+--------+-------+-------------+
解决方案
用 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
推荐阅读
- javascript - 多次执行相同的 firebase 绑定(.on() 方法)
- azure - 写入 Azure 存储 Blob (PowerShell)
- javascript - 在 Javascript 中解析 XML 值
- iis - 创建虚拟目录 mydomain.com
- azure - Azure Pipline 部署到 Kubernetes:覆盖映像参考
- scheme - 在列表中返回正数的方案程序仅返回 t/f
- javascript - Angular:在定义之前使用本地引用
- java - 遍历java中的值
- c# - 对于单元测试如何使命名空间派生?
- nginx - 有什么方法可以在 nginx 中仅记录请求/响应的标头大小?