python - 通过平均或重新组合一个 numpy 2d 数组来调整大小

标签 python numpy slice binning

我正在尝试在 python 中重新实现一个 IDL 函数:

http://star.pst.qub.ac.uk/idl/REBIN.html

通过平均将二维数组缩小一个整数因子。

例如:

>>> a=np.arange(24).reshape((4,6))
>>> a
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]])

我想通过取相关样本的平均值将其调整为 (2,3),预期输出为:

>>> b = rebin(a, (2, 3))
>>> b
array([[  3.5,   5.5,  7.5],
       [ 15.5, 17.5,  19.5]])

b[0,0] = np.mean(a[:2,:2]), b[0,1] = np.mean(a[:2,2:4]) 和以此类推。

我相信我应该 reshape 为一个 4 维数组,然后在正确的切片上取平均值,但无法弄清楚算法。你有什么提示吗?

最佳答案

这是一个基于 the answer you've linked 的示例(为清楚起见):

>>> import numpy as np
>>> a = np.arange(24).reshape((4,6))
>>> a
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]])
>>> a.reshape((2,a.shape[0]//2,3,-1)).mean(axis=3).mean(1)
array([[  3.5,   5.5,   7.5],
       [ 15.5,  17.5,  19.5]])

作为一个函数:

def rebin(a, shape):
    sh = shape[0],a.shape[0]//shape[0],shape[1],a.shape[1]//shape[1]
    return a.reshape(sh).mean(-1).mean(1)

关于python - 通过平均或重新组合一个 numpy 2d 数组来调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8090229/

相关文章:

python - 按体素打乱 4 维时间序列

count - 按字母顺序排列的最长子串

python - 哪些 Scipy 模块实际上调用了 Numpy 模块?

python - 选择当前行以及上面满足条件的 3 行

python - 我的网页没有显示使用Flask的图像

python - Pandas 打开 json 文件 JSON -ValueError : Expected object or value

python - 我如何通过 scipy/numpy 或 sympy 实现第一类球形 hankel 函数?

python - 使用索引手动切片列表,Python

python - 在 ndarray 中切片多个维度

python - 使用 vtk 时导入的 undefined variable