Numpy rebinning a 2D array

后端 未结 3 1560
孤街浪徒
孤街浪徒 2021-02-08 04:50

I am looking for a fast formulation to do a numerical binning of a 2D numpy array. By binning I mean calculate submatrix averages or cumulative values. For ex. x = numpy.arange(

3条回答
  •  醉梦人生
    2021-02-08 05:17

    See the SciPy Cookbook on rebinning, which provides this snippet:

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

提交回复
热议问题