Search code examples
pythonpandasdataframecumsum

How to find the row index of Pandas dataframe at which a column CumSum equals X?


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?


Solution

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

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