-->

numpy的重排的2D阵列(Numpy rebinning a 2D array)

2019-08-17 00:57发布

我要寻找一个快速的配方做了2D numpy的阵列的数值分级。 通过分档我的意思是小矩阵计算平均值或累积值。 对于前。 X = numpy.arange(16).reshape(4,4)将被分裂在4子矩阵每个2×2的,并给出numpy.array([[2.5,4.5],[10.5,12.5]]),其中2.5 = numpy的。平均([0,1,4,5])等...

如何以高效的方式执行这样的操作......我没有任何真正的ideay如何执行此...

非常感谢...

Answer 1:

您可以使用阵列的高维视图,并采取沿额外维度的平均:

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分裂rowsbcols 。 有一些方法可以处理其他案件,但你必须定义要则行为。



Answer 2:

见的SciPy的食谱上重新分组 ,它提供了这个片断:

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))


Answer 3:

我以为你只是想知道如何建立普遍执行良好,不使用数组的东西,就像一个功能numpy.reshape在你的榜样。 所以,如果性能真的很重要,你已经在使用numpy的,你可以写你自己的C代码,像NumPy这样做。 例如,实施人气指数是完全C.几乎numpy的一切事宜,其在性能方面的C.实现

然而,在这样做之前,你应该尝试在Python中实现代码,看看如果表现不够好。 尽量不要让Python代码尽可能高效。 如果仍然不能满足您的性能需求,走的C方式。

你可以阅读有关的文档 。



文章来源: Numpy rebinning a 2D array
标签: numpy binning