我试图通过取元素的平均值将numpy数组分组为较小的大小。例如,将100x100阵列中的平均5x5子阵列的foreach平均值创建20x20大小的阵列。由于需要处理大量数据,这是一种有效的方法吗?

最佳答案

我已经尝试过使用较小的阵列,因此请与您的阵列进行测试:

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)

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]])

关于python - 平均分组2D numpy数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4624112/

10-12 16:52