对2D numpy数组进行平均分组

22

我正在尝试将一个numpy数组按照平均值分组为更小的大小。例如,在一个100x100的数组中,对于每个5x5的子数组进行平均,以创建一个20x20的数组。由于我有大量需要处理的数据,这种方法是否有效?


类似于这个答案:https://dev59.com/S3bZa4cB1Zd3GeqPG4YP#18645174。 - Daniel
4个回答

33

我已经尝试了这个方法,用于更小的数组,请使用您自己的数组进行测试:

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

这是一个关于N维数组的概括 https://dev59.com/jZffa4cB1Zd3GeqP9o5M#73078468 - divenex

4
这很简单,但我觉得它可以更快:
from __future__ import division
import numpy as np
Norig = 100
Ndown = 20
step = Norig//Ndown
assert step == Norig/Ndown # ensure Ndown is an integer factor of Norig
x = np.arange(Norig*Norig).reshape((Norig,Norig)) #for testing
y = np.empty((Ndown,Ndown)) # for testing
for yr,xr in enumerate(np.arange(0,Norig,step)):
    for yc,xc in enumerate(np.arange(0,Norig,step)):
        y[yr,yc] = np.mean(x[xr:xr+step,xc:xc+step])

您可能也会发现scipy.signal.decimate很有趣。它在对数据进行下采样之前应用了比简单平均更复杂的低通滤波器,尽管您需要先对一个轴进行下采样,然后再对另一个轴进行下采样。


3

将一个2D数组在大小为NxN的子数组上取平均值:

height, width = data.shape
data = average(split(average(split(data, width // N, axis=1), axis=-1), height // N, axis=1), axis=-1)

2
不错!只是澄清一下,average和split是numpy函数。 - prl900

0
请注意,eumiro's approach 对掩码数组不起作用,因为 .mean(3).mean(1) 假定轴 3 上的每个平均值都是从相同数量的值计算出来的。如果您的数组中有掩码元素,则此假设不再成立。在这种情况下,您必须跟踪用于计算 .mean(3) 的值的数量,并将 .mean(1) 替换为加权平均。权重是用于计算 .mean(3) 的归一化值的数量。

以下是一个示例:

import numpy as np


def gridbox_mean_masked(data, Nbig, Nsmall):
    # Reshape data
    rshp = data.reshape([Nsmall, Nbig//Nsmall, Nsmall, Nbig//Nsmall])

    # Compute mean along axis 3 and remember the number of values each mean
    # was computed from
    mean3 = rshp.mean(3)
    count3 = rshp.count(3)

    # Compute weighted mean along axis 1
    mean1 = (count3*mean3).sum(1)/count3.sum(1)
    return mean1


# Define test data
big = np.ma.array([[1, 1, 2],
                   [1, 1, 1],
                   [1, 1, 1]])
big.mask = [[0, 0, 0],
            [0, 0, 1],
            [0, 0, 0]]
Nbig = 3
Nsmall = 1

# Compute gridbox mean
print gridbox_mean_masked(big, Nbig, Nsmall)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接