Home > Back-end >  Calculating the cumulative sum in a list starting at the next element and going through the list in
Calculating the cumulative sum in a list starting at the next element and going through the list in

Time:11-17

Let's say I got a list like this:

L = [600, 200, 100, 80, 20]

What is the most efficient way to calculate the cumulative sum starting from the next element for every element in the list.

The output of should thus be:

 x_1 = 400 (200   100   80   20)
 x_2 = 200 (100   80   20)
 x_3 = 20 (20)
 x_4 = 0

CodePudding user response:

try this:

    l = [600, 200, 100, 80, 20]
    res = [sum(l[i:]) for i in range(1, len(l))]
    print(res)

for your example the output should be [400, 200, 100, 20]

CodePudding user response:

try using cumsum

L = [600, 200, 100, 80, 20]
df=pd.DataFrame(L,columns=['Value'])
df['Running_Total'] = df['Value'].cumsum()
df['Running_Total2'] = df['Value'].expanding().sum()
print(df)

CodePudding user response:

You can use the sum functio sum(L)-L[0]

  • Related