Alberto Tono
Alberto Tono

Reputation: 324

NumPY: Undestand how to sum every n values in an array matrix

Hi folks,

 array([[  3.,  12.,  21.,  30.],
           [  3.,  12.,  21.,  30.],
           [  3.,  12.,  21.,  30.],
           [  3.,  12.,  21.,  30.],
            ...
           [  3.,  12.,  21.,  30.]
           [  3.,  12.,  21.,  30.],
           [  3.,  12.,  21.,  30.],
           [  3.,  12.,  21.,  30.]])

How to sum every 29 rows in the same column: (3+3+3+3...) 29times. Could be great to reshape the size of our array (1392, 8760) in a (48, 8760) after the sum of these values. I tried to look at the reshape and sum function but I am having a hard time to deeply understand how it works.

Upvotes: 1

Views: 1862

Answers (1)

user3483203
user3483203

Reputation: 51155

The general idea here is to add an additional dimension to your array to break it into n length chunks, then sum along the first axis.

Setup

a = np.zeros((1392, 8760))
chunk_size = 29

Using reshape and sum:

out = a.reshape(-1, chunk_size, a.shape[1]).sum(1)
print(out.shape)

(48, 8760)

Upvotes: 2

Related Questions