我正在尝试在 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/