Sum of few selected rows in a column

33 views Asked by At

Consider dataframe as follows:

     list1  

 0    2         
 1    5         
 2    4     
 3    8         
 4    4         
 5    7         
 6    8 

i want to write a code in pandas, in which "sum" will be the sum of subsequent elements in two rows in "list1", output will be as follows:

     list1      sum

 0     2        NaN 
 1     5        7       
 2     4        9       
 3     8        12      
 4     4        12  
 5     7        11      
 6     8        15  
1

There are 1 answers

0
jezrael On

Use rolling with sum:

df['sum'] = df['list1'].rolling(2).sum()
print (df)
   list1   sum
0      2   NaN
1      5   7.0
2      4   9.0
3      8  12.0
4      4  12.0
5      7  11.0
6      8  15.0