对列执行累积总和,但如果总和在 Pandas 中变为负数则重置为 0 [英] Perfrom cumulative sum over a column but reset to 0 if sum become negative in Pandas

查看:54
本文介绍了对列执行累积总和,但如果总和在 Pandas 中变为负数则重置为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样两列的熊猫数据框,

I have a pandas dataframe with two columns like this,

Item    Value
0   A   7
1   A   2
2   A   -6
3   A   -70
4   A   8
5   A   0

我想对列进行累计求和,Value.但是,如果值变为负,则在创建累积总和时,我想将其重置为 0.

I want to cumulative sum over the column, Value. But while creating the cumulative sum if the value becomes negative I want to reset it back to 0.

我目前正在使用如下所示的循环来执行此操作,

I am currently using a loop shown below to perform this,

sum_ = 0
cumsum = []

for val in sample['Value'].values:
    sum_ += val
    if sum_ < 0:
        sum_ = 0
    cumsum.append(sum_)

print(cumsum) # [7, 9, 3, 0, 8, 8]

我正在寻找一种更有效的方法来在纯 Pandas 中执行此操作.

I am looking for a more efficient way to perform this in pure pandas.

推荐答案

稍微修改一下这个方法也很慢 numba 解决方案

Slightly modify also this method is slow that numba solution

sumlm = np.frompyfunc(lambda a,b: 0 if a+b < 0 else a+b,2,1)
newx=sumlm.accumulate(df.Value.values, dtype=np.object)
newx
Out[147]: array([7, 9, 3, 0, 8, 8], dtype=object)

<小时>

numba 解决办法

from numba import njit
@njit
def cumli(x, lim):
    total = 0
    result = []
    for i, y in enumerate(x):
        total += y
        if total < lim:
            total = 0
        result.append(total)
    return result
cumli(df.Value.values,0)
Out[166]: [7, 9, 3, 0, 8, 8]

这篇关于对列执行累积总和,但如果总和在 Pandas 中变为负数则重置为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆