how to get the neighboring elements in a numpy array with taking boundaries into account?

前端 未结 4 827
不知归路
不知归路 2021-01-01 02:40

I want to get the neighbors of the certain element in the numpy array. Lets consider following example

    a = numpy.array([0,1,2,3,4,5,6,7,8,9])
         


        
4条回答
  •  囚心锁ツ
    2021-01-01 03:09

    import numpy as np
    a = np.array([0,1,2,3,4,5,6,7,8,9])
    num_neighbor=3    
    
    for index in range(len(a)):
        left = a[:index][-num_neighbor:]
        right= a[index+1:num_neighbor+index+1]
        print(index,left,right)
    

    yields

    (0, array([], dtype=int32), array([1, 2, 3]))
    (1, array([0]), array([2, 3, 4]))
    (2, array([0, 1]), array([3, 4, 5]))
    (3, array([0, 1, 2]), array([4, 5, 6]))
    (4, array([1, 2, 3]), array([5, 6, 7]))
    (5, array([2, 3, 4]), array([6, 7, 8]))
    (6, array([3, 4, 5]), array([7, 8, 9]))
    (7, array([4, 5, 6]), array([8, 9]))
    (8, array([5, 6, 7]), array([9]))
    (9, array([6, 7, 8]), array([], dtype=int32))
    

    The reason why a[index-num_neighbor:index] does not work when index is because of slicing rules #3 and #4:

    Given s[i:j]:

    If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted.

    The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

    So when index=1, then a[index-num_neighbor:index] = a[-2:1] = a[10-2:1] = a[8:1] = [].

提交回复
热议问题