我正在寻找一种快速的方法对2D numpy数组进行数字分组。所谓分组是指计算子矩阵的平均值或累积值。例如,x = numpy.arange(16).reshape(4, 4) 将被分割为4个2x2的子矩阵,并给出numpy.array([[2.5,4.5],[10.5,12.5]]),其中2.5=numpy.average([0,1,4,5])等...
如何以高效的方式执行此操作...我真的不知道如何执行这个操作......
非常感谢...
我正在寻找一种快速的方法对2D numpy数组进行数字分组。所谓分组是指计算子矩阵的平均值或累积值。例如,x = numpy.arange(16).reshape(4, 4) 将被分割为4个2x2的子矩阵,并给出numpy.array([[2.5,4.5],[10.5,12.5]]),其中2.5=numpy.average([0,1,4,5])等...
如何以高效的方式执行此操作...我真的不知道如何执行这个操作......
非常感谢...
In [12]: a = np.arange(36).reshape(6, 6)
In [13]: a
Out[13]:
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]])
In [14]: a_view = a.reshape(3, 2, 3, 2)
In [15]: a_view.mean(axis=3).mean(axis=1)
Out[15]:
array([[ 3.5, 5.5, 7.5],
[ 15.5, 17.5, 19.5],
[ 27.5, 29.5, 31.5]])
一般来说,如果您想要将形状为(a, b)
的数组分成(rows, cols)
个容器,则应使用.reshape(rows // a, a, cols // b, b)
进行重塑。还要注意.mean
的顺序很重要,例如a_view.mean(axis=1).mean(axis=3)
会引发错误,因为a_view.mean(axis=1)
只有三个维度,尽管a_view.mean(axis=1).mean(axis=2)
可以正常工作,但这使得理解所发生的情况变得更加困难。
正如现在的代码一样,仅当您可以将整数个容器放入数组中时才能正常运行,即a
可以整除rows
并且b
可以整除cols
。有方法可以处理其他情况,但您必须定义所需的行为。
.mean(axis=(1,3))
将其压缩在一起! - seberg[[0, 1], [6, 7]]
的平均值是a_view.mean(axis=3).mean(axis=1)
的第[0, 0]
项。 - Jaimereshape(3, 2, 3, 2)
)不是2x2子矩阵的数组,尽管结果仍然是正确的。 - shaman.sirdef rebin(a, *args):
'''rebin ndarray data into a smaller ndarray of the same rank whose dimensions
are factors of the original dimensions. eg. An array with 6 columns and 4 rows
can be reduced to have 6,3,2 or 1 columns and 4,2 or 1 rows.
example usages:
>>> a=rand(6,4); b=rebin(a,3,2)
>>> a=rand(6); b=rebin(a,2)
'''
shape = a.shape
lenShape = len(shape)
factor = asarray(shape)/asarray(args)
evList = ['a.reshape('] + \
['args[%d],factor[%d],'%(i,i) for i in range(lenShape)] + \
[')'] + ['.sum(%d)'%(i+1) for i in range(lenShape)] + \
['/factor[%d]'%i for i in range(lenShape)]
print ''.join(evList)
return eval(''.join(evList))