Home > Software engineering >  Numpy How to make a moving(growing) sum of table contents without a for loop?
Numpy How to make a moving(growing) sum of table contents without a for loop?

Time:12-23

Due to the fact english is not my first language it is very hard to me to explain simply the problem I am trying to solve in the topic, and thus I am sorry.

So instead of trying to explain with bare words I am going to give an example.

Let's say we have an array that is instantiated like this:

weight = np.arange(1, (n   1)).astype('float64')

So the array looks like this:

[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]

Now what I want to do is to have an array of moving sums(let's call it norm), summarizing the array norm and operations would look like this:

index, norm(new array), weight, operation
  0        1               1     0 1 = 1
  1        3               2     0 1 2 = 3
  2        6               3     0 1 2 3 = 6
  3        10              4     0 1 2 3 4 = 10
  .         .              .      .
  .         .              .      .
  .         .              .      .
  9        55              10    0 1 2 3 ... 10 = 55

I hope it is understandable. How do I achieve this result without looping through the weight array?

CodePudding user response:

numpy.cumsum does exactly this:

np.cumsum(weight)
  • Related