NumPy:对矩阵的每n列求和 [英] NumPy: sum every n columns of matrix

查看:1869
本文介绍了NumPy:对矩阵的每n列求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对矩阵的每n列求和.如何在不使用for循环的情况下以简单的方式做到这一点?这就是我现在拥有的:

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)

结果将是

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

如何矢量化此操作?

推荐答案

这是一种方法;首先将x整形为3D数组,然后在最后一个轴上求和:

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

这篇关于NumPy:对矩阵的每n列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆