Search code examples
pythonarraysloopsscipycumsum

Cumsum returning a vector in python


I have my array, say: [10, 6, 4, 12]. I am interested in finding a vector of cumulative sums, i.e.: [10, 16, 20, 32]. Obvious approach would be to use a for loop:

r = []
for ind in range(4):
  r.append(s[ind])  # s is [10, 6, 4, 12]
r = cumsum(r)

However, this seems really inefficient. I want to ask if there is a pre-defined function or I should specify specific arguments in cumsum.


Solution

  • there are many ways like np.cumsum or python 3.2+ you can use itertools.accumulate

    By Itertool:

    l = [10, 6, 4, 12]
    
    from itertools import accumulate
    
    print(list(accumulate(l)))
    

    output:

    [10, 16, 20, 32]
    

    Using numpy:

    import numpy as np
    
    print(np.cumsum(l))
    

    output:

    [10, 16, 20, 32]