For*_*zaa 1 python numpy sum matrix vectorization
我想对矩阵的每 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)
Run Code Online (Sandbox Code Playgroud)
结果将是
array([[ 3., 12., 21., 30.],
[ 3., 12., 21., 30.],
...
[ 3., 12., 21., 30.]])
Run Code Online (Sandbox Code Playgroud)
如何矢量化此操作?
这是一种方法;首先重塑x为 3D 数组,然后在最后一个轴上求和:
>>> 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]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3434 次 |
| 最近记录: |