wrapping around slices in Python / numpy

后端 未结 7 2250
耶瑟儿~
耶瑟儿~ 2020-12-05 17:41

I have a numpy array, and I want to get the \"neighbourhood\" of the i\'th point. Usually the arrays I\'m using are two-dimensional, but the following 1D example illustrates

7条回答
  •  鱼传尺愫
    2020-12-05 18:06

    I know this question is old, but should mention scipy.ndimage.filter.generic_filter.

    It has a mode='wrap' option, plus it handles the application of the neighbor function.

    import scipy.ndimage as nd
    
    A = np.array([0,10,20,30,40,50,60,70,80,90])
    

    Say you have a neighbor function:

    def nbf(arr):
        return sum(arr)
    

    To apply the neighbor function to every 5, with wrapped values at the edges:

    C = nd.generic_filter(A, nbf, 5, mode='wrap')
    
    print(C)
    [200 150 100 150 200 250 300 350 300 250]
    

提交回复
热议问题