NumPy:矩阵每n列求和

2024-05-13 13:53:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对矩阵的每n列求和。我怎样才能在不使用for循环的情况下以一种简单的方式完成呢?这就是我现在所拥有的:

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)

结果是

^{pr2}$

如何将此操作矢量化?在


Tags: offorsizenp方式情况矩阵result
1条回答
网友
1楼 · 发布于 2024-05-13 13:53:43

有一种方法:首先将x重塑为三维数组,然后在最后一个轴上求和:

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

相关问题 更多 >