-1

Consider the following DataFrame df:

index    A
    0   -1
    1    0
    2    1
    3   -1  # <==== here, df['A'].cumsum() == 0, starting from last row 
    4   -1
    5   -1
    6    1
    7   -1
    8    1
    9    1
    10   1

I am trying to determine at which row the cumulative sum of Acounted from the last row — equals zero.

In this post, the solution will not work if a column contains negative values, which is my case.

Moving from top to bottom I presume

df[df['A'].cumsum() == 0]

would work but this procedure would need to be reversed.

Do you have any pointers in how to do this?

pepe
  • 9,799
  • 25
  • 110
  • 188

2 Answers2

3

You can use [::-1] to get the reveresed cumsum. This will return all results where the cumsum = 0:

df[df['A'][::-1].cumsum() == 0]

   index    A
0   0      -1
3   3      -1

If you just want the last then do:

df[df['A'][::-1].cumsum() == 0].iloc[-1]

index    3
A       -1
David Erickson
  • 16,433
  • 2
  • 19
  • 35
1

[::-1] can reverse any series or list:

df[df['A'][::-1].cumsum()==0]
Wasif
  • 14,755
  • 3
  • 14
  • 34