Perfrom在列上的累积总和,但如果总和在熊猫中变为负数,则重置为0

Sre*_* TP 10 python pandas

我有一个带有两列的pandas数据框,

Item    Value
0   A   7
1   A   2
2   A   -6
3   A   -70
4   A   8
5   A   0
Run Code Online (Sandbox Code Playgroud)

我想在列上累计总和Value。但是在创建累计和时,如果值变为负数,我想将其重置为0。

我目前正在使用下面显示的循环执行此操作,

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]
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种更有效的方式在纯大熊猫中执行此操作。

WeN*_*Ben 7

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

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)
Run Code Online (Sandbox Code Playgroud)

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]
Run Code Online (Sandbox Code Playgroud)

  • @Erfan不确定速度,但是因为我在上面列出了链接,所以op可以选择他想要的一个:-) (2认同)