1

I have a numpy array generated by some earlier code which needs to be added blockwise. For example, array a has 32 entries and should be added such that the new array b has 4 entries and b[0] has numbers 0-7, b[1] has 8-15 and so on. See example below of how to do it manually.

import numpy as np
a = np.random.rand(32)
b = np.zeros(4)
b[0] = np.sum(a[0:8])
b[1] = np.sum(a[8:16])
b[2] = np.sum(a[16:24])
b[3] = np.sum(a[24:32])

Now I know that I can do the summation using a for loop, but I was hoping for something more fancy, as I am working with rather large arrays. I am aware of numpy's great slicing magic, so I imagine something like this could be used.

1 Answer 1

3

I would use something like this:

#import random
import numpy as np
np.random.seed(11) # random.seed doesnt affect numpy computation as pointed out in the comments 

a = np.random.rand(32)
b = np.zeros(4)
a = np.reshape(a, (4,-1))
b = np.sum(a, axis=1)
Sign up to request clarification or add additional context in comments.

4 Comments

What is the -1 means?
One of the dimensions in reshape can be -1. In this case, the value is inferred from the length of the array and the remaining dimensions. Complete doc here numpy.org/doc/stable/reference/generated/…
This works great, thanks. Only tiny improvement would be to use np.random.seed, as currently your seed does not affect numpy and every run will get different results. Note that this may be version dependent, I recall some libraries directly using random its internal state, but at least recent versions of numpy keep track of their own state, unaffected by other packages.
Thanks, will update the answer accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.