laolux
laolux

Reputation: 1565

Add numpy array in blockwise

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.

Upvotes: 1

Views: 60

Answers (1)

mibrahimy
mibrahimy

Reputation: 732

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)

Upvotes: 3

Related Questions