我正在寻找一个快速的公式来做一个2D numpy数组的数值装仓。通过binning我的意思是计算子矩阵的平均值或累计值。例如。 x = numpy.arange(16).reshape(4,4)将被分解为2x2的4个子矩阵,并给出numpy.array([[2.5,4.5],[10.5,12.5]]),其中2.5 = numpy。平均([0,1,4,5])等...Numpy重组2D数组
如何以有效的方式执行这样的操作...我真的没有任何想法如何执行此操作...
非常感谢...
我正在寻找一个快速的公式来做一个2D numpy数组的数值装仓。通过binning我的意思是计算子矩阵的平均值或累计值。例如。 x = numpy.arange(16).reshape(4,4)将被分解为2x2的4个子矩阵,并给出numpy.array([[2.5,4.5],[10.5,12.5]]),其中2.5 = numpy。平均([0,1,4,5])等...Numpy重组2D数组
如何以有效的方式执行这样的操作...我真的没有任何想法如何执行此操作...
非常感谢...
您可以使用阵列的高维视图,并取平均值沿额外维度:
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)
可以正常工作,但它会使得更难理解正在发生的事情。
AS是,上面的代码只工作,如果如果a
划分rows
和b
划分cols
可以适合你的数组内箱的整数倍,即。有办法处理其他情况,但是你必须定义你想要的行为。
在numpy 1.7。你可以将它压缩到'.mean(axis =(1,3))'! – seberg 2013-02-17 01:19:27
我不知道这个重塑是可能的,太棒了!不幸的是,平均值是按照顺序依赖的,因此如何获得前者的平均值。在你的例子中的2,2的子矩阵(我的意思是角0,1,6,7等)? – user1187727 2013-02-17 15:29:48
@ user1187727我不认为我理解你的问题,但是'[[0,1],[6,7]]'的平均值是'a_view.mean(axis = 1)'的项['0,0] 3).mean(轴= 1)'。 – Jaime 2013-02-17 15:36:14
见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))
是保证,以适应小矩阵,到底是什么?你有1.7吗?可用(这就是整洁,没有必要)? – seberg 2013-02-17 00:59:01
我已经numpy 1.8dev,但我的工作得到旧版本... – user1187727 2013-02-17 15:31:39