如何评估数组块中的值之和

我有数据阵列,形状为100×100.我想把它分成5×5块,每个块有20×20网格.我想要的每个块的值是其中所有值的总和.

是否有更优雅的方式来实现它?

x = np.arange(100)
y = np.arange(100)
X, Y = np.meshgrid(x, y)
Z = np.cos(X)*np.sin(Y)
Z_new = np.zeros((5, 5))
for i in range(5):
  for j in range(5):
    Z_new[i, j] = np.sum(Z[i*20:20+i*20, j*20:20+j*20])

这是基于索引,如果基于x?

x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
X, Y = np.meshgrid(x, y)
Z = np.cos(X)*np.sin(Y)
x_new = np.linspace(0, 1, 15)
y_new = np.linspace(0, 1, 15)

Z_new?

简单地说reshape将这两个轴中的每一个分成两个,每个轴具有形状(5,20),然后沿着长度为20的轴减小总和,就像这样 –

Z_new = Z.reshape(5,20,5,20).sum(axis=(1,3))

功能相同但可能更快的选项np.einsum

Z_new = np.einsum('ijkl->ik',Z.reshape(5,20,5,20))

运行时测试 –

In [18]: x = np.arange(100)
    ...: y = np.arange(100)
    ...: X, Y = np.meshgrid(x, y)
    ...: Z = np.cos(X)*np.sin(Y)
    ...: 

In [19]: %timeit Z.reshape(5,20,5,20).sum(axis=(1,3))
10000 loops, best of 3: 49.5 µs per loop

In [20]: %timeit np.einsum('ijkl->ik',Z.reshape(5,20,5,20))
10000 loops, best of 3: 46.7 µs per loop
https://stackoverflow.com/questions/36383107/how-to-evaluate-the-sum-of-values-within-array-blocks

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:如何评估数组块中的值之和