我正在寻找一种快速的公式来做一个二维numpy数组的数值仓储。所谓入库,我是指计算子矩阵平均值或累积值。对于ex。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)等。
如何以有效的方式执行这样的操作...我真的不知道该怎么做...
非常感谢。
发布于 2013-02-17 09:01:46
您可以使用数组的高维视图,并沿额外维度取平均值:
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]])通常,如果您希望(rows, cols)数组具有形状为(a, b)的存储箱,则应该将其重塑为.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)可以很好地工作,但它使理解发生了什么变得更加困难。
现在,上面的代码只有在数组中可以容纳整数个rows时才有效,即如果a除以rows,而b除以cols。有一些方法可以处理其他情况,但您必须定义您想要的行为。
发布于 2014-02-21 11:14:58
请参阅the SciPy Cookbook on rebinning,它提供了以下代码片段:
def 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))发布于 2013-02-17 08:40:06
我假设您只想知道如何构建一个性能良好并对数组执行某些操作的函数,就像示例中的numpy.reshape一样。因此,如果性能真的很重要,并且您已经在使用numpy,那么您可以为此编写自己的C代码,就像numpy一样。例如,arange的实现完全是用C实现的,几乎所有与numpy有关的性能都是用C实现的。
但是,在这样做之前,您应该尝试用python实现代码,看看性能是否足够好。试着让python代码尽可能高效。如果它仍然不能满足您的性能需求,请使用C方法。
你可以在docs上读到这一点。
https://stackoverflow.com/questions/14916545
复制相似问题