I'm trying to create a column with cumulative sum that resets to zero when the cumsum gets below zero. I the following data:
id | treatment | value |
---|---|---|
1 | drugs | 66 |
1 | drugs | 33 |
1 | drugs | -100 |
1 | drugs | 11 |
1 | drugs | 30 |
1 | drugs | -50 |
The desired result:
id | treatment | days | cumsum |
---|---|---|---|
1 | drugs | 66 | 66 |
1 | drugs | 33 | 99 |
1 | drugs | -100 | 0 |
1 | drugs | 11 | 11 |
1 | drugs | 30 | 41 |
1 | drugs | -50 | 0 |
Is there a solution close to this attempt?
df.groupby(['id','treatment']).days.apply(lambda x: 0 if x.cumsum() < 0 else x.cumsum())