wrapping around slices in Python / numpy

后端 未结 7 2269
耶瑟儿~
耶瑟儿~ 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:00

    You can use the np.pad routine like this:

    A = np.array([0,10,20,30,40,50,60,70,80,90])
    A = np.pad(A, 2, 'wrap')
    print(A)
    [80, 90,  0, 10, 20, 30, 40, 50, 60, 70, 80, 90,  0, 10]
    

    Say you have a neighbor function:

    def nbf(arr):
        return sum(arr)
    

    To apply the neighbor function to every 5 you need to be careful about your start and end indices (in the range(...) command) and the relative slice you take from A.

    B = [nbf(A[i-2:i+3]) for i in range(2,12)]
    print(B)
    [200, 150, 100, 150, 200, 250, 300, 350, 300, 250]
    

提交回复
热议问题