NumPy: sum every n columns of matrix

2019-06-02 09:33发布

I'd like to sum every n columns of a matrix. How can I do that in a simple way without using a for loop? This is what I have now:

n = 3  #size of a block we need to sum over
total = 4  #total required sums
ncols = n*total
nrows = 10
x = np.array([np.arange(ncols)]*nrows)

result = np.empty((total,nrows))
for i in range(total):
    result[:,i] =  np.sum(x[:,n*i:n*(i+1)],axis=1)

The result will be

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

How can I vectorize this operation?

1条回答
可以哭但决不认输i
2楼-- · 2019-06-02 10:16

Here's one way; first reshape x to a 3D array and then sum over the last axis:

>>> x.reshape(-1, 4, 3).sum(axis=2)
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],
       [ 3, 12, 21, 30],
       [ 3, 12, 21, 30]])
查看更多
登录 后发表回答