Python pandas cumsum() reset after hitting max

Here’s an example of how you might do this by iterating over each row in the dataframe. I created new data for the example for simplicity:

df = pd.DataFrame({'TimeDelta': np.random.normal( 900, 60, size=100)})
print df.head()
    TimeDelta
0  971.021295
1  734.359861
2  867.000397
3  992.166539
4  853.281131

So let’s do an accumulator loop with your desired 3000 max:

maxvalue = 3000

lastvalue = 0
newcum = []
for row in df.iterrows():
    thisvalue =  row[1]['TimeDelta'] + lastvalue
    if thisvalue > maxvalue:
        thisvalue = 0
    newcum.append( thisvalue )
    lastvalue = thisvalue

Then put the newcom list into the dataframe:

df['newcum'] = newcum
print df.head()
    TimeDelta       newcum
0  801.977678   801.977678
1  893.296429  1695.274107
2  935.303566  2630.577673
3  850.719497     0.000000
4  951.554206   951.554206

Leave a Comment