Forzaa Forzaa - 7 days ago 6
Python Question

NumPy: sum every n columns of matrix

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?

Answer

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]])
Comments