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

Issue

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

Solution

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

Answered By – onyambu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published