达到某个值后重置累积和并将标志设置为 1

Resetting Cumulative Sum once a value is reached and set a flag to 1

我无法想出一种方法来对列执行累计和并在它达到特定值后创建一个标志。

所以给定一个数据框:

df = pd.DataFrame([[5,1],[6,1],[30,1],[170,0],[5,1],[10,1]],columns = ['a','b'])

     a  b
0    5  1
1    6  1
2   30  1
3  170  0
4    5  1
5   10  1

对于 A 列,我想执行累计和,如果达到最大值,则将“标志”列值设置为 1。达到最大值后,它将重置为 0。在这种情况下,最大值为 40。任何超过 40 的累积和都会触发重置

Desired Output

     a  b  Flag
0    5  1     0
1   11  1     0
2   41  1     1
3  170  0     1
4    5  1     0
5   15  1     0

如有任何帮助,我们将不胜感激!

“普通”cumsum()在这里没用,因为这个函数“不知道” 在哪里重新开始求和。

您可以使用以下自定义函数来完成:

def myCumSum(x, thr):
    if myCumSum.prev >= thr:
        myCumSum.prev = 0
    myCumSum.prev += x
    return myCumSum.prev

这个函数是“有记忆的”(来自之前的调用)- prev,所以有 是一种“知道”从哪里重新开始的方法。

为加快执行速度,定义此函数的向量化版本:

myCumSumV = np.vectorize(myCumSum, otypes=[np.int], excluded=['thr'])

然后执行:

threshold = 40
myCumSum.prev = 0  # Set the "previous" value
# Replace "a" column with your cumulative sum
df.a = myCumSumV(df.a.values, threshold)
df['flag'] = df.a.ge(threshold).astype(int)  # Compute "flag" column

结果是:

     a  b  flag
0    5  1     0
1   11  1     0
2   41  1     1
3  170  0     1
4    5  1     0
5   15  1     0