Search code examples
pythonadditiondataframe

Sum up previous values of a column


I am dealing with a rather simple problem, but cannot find a solution.

Let's consider the following table:

A

1

4

5

2

I would like to create a new column (B) the sum of Row A until the respective index:

A B

1 1

4 5

5 10

2 12

I was thinking and searching for a solution but could not find one. You have an idea how to proceed?

My approach:

  1. create default column with 0. df['B']=0
  2. df['B']=df.B.shift()+df.A

Is there a way to solve the problem in Python?


Solution

  • Do:

    lA = [1,4,5,2]
    
    lB = [sum(l[0:i+1]) for i in range(len(l))]
    

    And if you don't get list comprehension here is a more verbose version of the code:

    lB = []
    for i in range(len(l)):
        lStuffAbove = l[0:i+1]
        lB.append(sum(lStuffAbove))