Home > Enterprise >  Find cumulative maximum of a pandas series, but reset the cumulative maximum when 0 is encountered
Find cumulative maximum of a pandas series, but reset the cumulative maximum when 0 is encountered

Time:06-11

Consider the series below:

  1. 100
  2. 102
  3. 101
  4. 103
  5. 0
  6. 12
  7. 123
  8. 14

I want the result to be as follows:

  1. 100
  2. 102
  3. 102
  4. 103
  5. 0
  6. 12
  7. 123
  8. 123

CodePudding user response:

Let d be the variable containing your series, then groupby the cummulative sum of d == 0 and then obtain the cummax

d.groupby(d.eq(0).cumsum()).cummax()
Out[37]: 
0    100
1    102
2    102
3    103
4      0
5     12
6    123
7    123
  • Related