2D numpy数组的块平均值(在两个维度中)

2024-06-16 10:19:18 发布

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

这个问题与Block mean of numpy 2D array有关(实际上标题几乎相同!),只是我的案例是一个概括。我想把一个二维数组分成两个方向上的子块,然后取块的平均值。(链接示例仅在一维中分割数组)

因此,如果我的数组是:

import numpy as np 
a=np.arange(16).reshape((4,4))

array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

如果我的子块大小为2x2,那么我想要的答案是

array([[ 2.5,  4.5],
       [10.5, 12.5]])

我能想到的唯一方法是一次仔细地在一个维度上重塑:

np.mean(np.mean(a.reshape((2,2,-1)),axis=1).reshape((-1,2,2)),axis=2)

这给出了正确的解决方案,但有点混乱,我想知道是否有更干净更简单的代码来做同样的事情,也许是一些我不知道的numpy阻塞函数


Tags: ofnumpy标题np数组mean方向block
1条回答
网友
1楼 · 发布于 2024-06-16 10:19:18

你可以做:

rows, cols = a.shape

# sample data
a=np.arange(24).reshape((6,4))

a.reshape(rows//2, 2, cols//2, 2).mean(axis=(1,-1))

输出:

array([[ 2.5,  4.5],
       [10.5, 12.5],
       [18.5, 20.5]])

相关问题 更多 >