Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

numpy.cumsum does exactly this:

np.cumsum(weight)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading