Search code examples
pythonpython-3.xnumpynumpy-ndarraynumpy-einsum

Accumulated sum of 2D array


Suppose I have a 2D numpy array like below

dat = np.array([[1,2],[3,4],[5,6],[7,8])

I want to get a new array with each row equals to the sum of its previous rows with itself, like the following

first row: [1,2]
second row: [1,2] + [3,4] = [4,6]
third row: [4,6] + [5,6] = [9,12]
forth row: [9,12] + [7,8] = [16,20]

So the array would be like

dat = np.array([[1,2],[4,6],[9,12],[16,20])    

Solution

  • np.cumsum is what you are looking for:

    dat = np.array([[1,2],[3,4],[5,6],[7,8]])
    result = np.cumsum(dat, axis=0)