python - 对一列执行累积总和,但如果总和在 Pandas 中变为负数,则重置为 0

标签 python pandas

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

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

我想对列 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]

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

最佳答案

稍微修改一下也是这个方法慢一点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)

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]

关于python - 对一列执行累积总和,但如果总和在 Pandas 中变为负数,则重置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57510604/

相关文章:

python - 在 python (pandas) 中将纳秒修剪为 100 纳秒

python - 如何使用 python pytest 断言 2 个数据帧

python - NetworkX From_Pandas_dataframe

Python Pandas : read csv with N columns where N is specified in the some other column

Python的日期时间转换

python - 查找自上次使用 python imaplib2 检查后添加到 imap 邮箱的新邮件?

python - Pandas Dataframe asFreq 改变索引的数据类型

python - nn.Embedding 模块如何直观地与一般嵌入的概念相关联?

python - 如何在 Python 中查找所有出现的模式及其索引

python - 对 DataFrame 中的 NaN 行应用 Map,Python 3.6