平均分组2D numpy数组

Roy*_*Roy 19 python numpy

我试图通过取平均值来将numpy数组分组为更小的数组.例如,在100x100阵列中取平均foreach 5x5子阵列以创建20x20大小的阵列.由于我需要操作大量数据,这是一种有效的方法吗?

eum*_*iro 26

我已经尝试过这个小阵列,所以用你的测试吧:

import numpy as np

nbig = 100
nsmall = 20
big = np.arange(nbig * nbig).reshape([nbig, nbig]) # 100x100

small = big.reshape([nsmall, nbig//nsmall, nsmall, nbig//nsmall]).mean(3).mean(1)
Run Code Online (Sandbox Code Playgroud)

6x6 - > 3x3的示例:

nbig = 6
nsmall = 3
big = np.arange(36).reshape([6,6])
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35]])

small = big.reshape([nsmall, nbig//nsmall, nsmall, nbig//nsmall]).mean(3).mean(1)

array([[  3.5,   5.5,   7.5],
       [ 15.5,  17.5,  19.5],
       [ 27.5,  29.5,  31.5]])
Run Code Online (Sandbox Code Playgroud)