【问题标题】:block mean of 2D numpy array (in both dimensions)2D numpy 数组的块均值(二维)
【发布时间】:2021-05-15 13:09:11
【问题描述】:

这个问题和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 阻塞函数?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

    • 当然是双轴意思(doh!) - 很好的双正斜杠 int(n/m) - 我也不知道...谢谢!
    猜你喜欢
    • 2012-12-23
    • 2019-03-02
    • 2021-06-19
    • 2017-12-13
    • 2020-12-09
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2021-01-17
    相关资源
    最近更新 更多