0

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])    
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Nicolas H
  • 535
  • 3
  • 13

1 Answers1

1

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)
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33