Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of previous rows values

how I can sum previous rows values and current row value to a new column? My current output:

index,value
0,1
1,2
2,3
3,4
4,5

My goal output is:

index,value,sum
0,1,1
1,2,3
2,3,6
3,4,10
4,5,15

I know that this is easy to do with Excel, but I'm looking solution to do with pandas.

My code:

import random, pandas

recordlist=[1,2,3,4,5]

df=pandas.DataFrame(recordlist, columns=["Values"])
like image 609
Juho M Avatar asked Apr 13 '17 15:04

Juho M


1 Answers

use cumsum

df.assign(sum=df.value.cumsum())

       value  sum
index            
0          1    1
1          2    3
2          3    6
3          4   10
4          5   15

Or

df['sum'] = df.value.cumsum()
df

       value  sum
index            
0          1    1
1          2    3
2          3    6
3          4   10
4          5   15

If df is a series

pd.DataFrame(dict(value=df, sum=df.cumsum())
like image 192
piRSquared Avatar answered Oct 22 '22 21:10

piRSquared