python - pandas cumsun - 达到最大值后重置或 ID 更改时重置

标签 python pandas timedelta cumsum

根据这个问题

Python pandas cumsum() reset after hitting max

我想在达到最大值后重置累积和当 ID 更改时重置。

Transaction_ID  Time            TimeDelta       CumSum[ms]
1              00:00:04.500     00:00:00.000    000
1              00:00:04.600     00:00:00.100    100
1              00:00:04.762     00:00:00.162    262
2              00:00:05.543     00:00:00.781    1043
2              00:00:09.567     00:00:04.024    5067
2              00:00:10.654     00:00:01.087    6154
2              00:00:14.300     00:00:03.646    9800
3              00:00:14.532     00:00:00.232    10032
3              00:00:16.500     00:00:01.968    12000
3             00:00:17.543     00:00:01.043    13043

最佳答案

检查链接中的函数,并使用groupby构建函数

def yourcumsum(x,maxvalue,lastvalue):
    newcum = []
    for row in x:
        thisvalue =  row + lastvalue
        if thisvalue > maxvalue:
            thisvalue = 0
        newcum.append( thisvalue )
        lastvalue = thisvalue
    return newcum


df['new'] = df.TimeDelta.dt.total_seconds()*1000

df['new' = df.groupby('Transaction_ID')['new'].transform(lambda x : yourcumsum(x,5000,0))
0       0.0
1     100.0
2     262.0
3     781.0
4    4805.0
5       0.0
6    3646.0
7     232.0
8    2200.0
9    3243.0
Name: new, dtype: float64

关于python - pandas cumsun - 达到最大值后重置或 ID 更改时重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67215079/

相关文章:

python - 导入错误 : cannot import name wsgiserver

python - 对 DataFrame 进行分组,按组大小和一行中的列值进行过滤?

python - 将第 n 行元素存储在列表 panda 数据框中

python - 时间增量到 Pandas 数据框中的字符串类型

python - 在Python中让线程休眠直到特定时间

java - 游戏以 60fps 的速度运行,但在减速后,它会以超快的速度运行几秒钟

python - 为什么我的 post-receive Hook 不能运行 virtualenv source 命令?

python - 在 Python 中重新排序嵌套列表条目

Python tkinter 按钮在按下时返回黑色

python - 两个元组作为Python列表中的一个元素