0

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  
Sreekiran A R
  • 3,123
  • 2
  • 20
  • 41
  • Change `mean` to `sum` from the solution in the duplicate link, and please search before asking next time. – cs95 Jan 13 '19 at 19:05

1 Answers1

0

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252