Search code examples
pandasdataframesum

Is there a way to produce a sum for rows below in a pandas dataframe?


I have a dataframe and I want to produce a column that shows the sum of all the rows below and including each row... for example:

A    B
2    10    i.e 2+4+3+1
4    8     i.e 4+3+1
3    4     i.e 3+1
1    1     

I have data in column 'A' and then I want 'B' to be a sum of the all the values of A including and below that point/row. Any ideas?


Solution

  • Use a reverse cumsum:

    df['B'] = df.loc[::-1, 'A'].cumsum()
    

    output:

       A   B
    0  2  10
    1  4   8
    2  3   4
    3  1   1