【发布时间】:2015-01-15 11:35:57
【问题描述】:
我想对矩阵的每 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)
结果是
array([[ 3., 12., 21., 30.],
[ 3., 12., 21., 30.],
...
[ 3., 12., 21., 30.]])
如何向量化这个操作?
【问题讨论】:
标签: python numpy matrix sum vectorization