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])
So I want to specify position 5 and want to get three neighbors from both sides. It can be done
index = 5
num_neighbor=3
left = a[index-num_neighbor:index]
right= a[num_neighbor+1:num_neighbor+index+1]
The above code does not take care of the boundaries… I want that i get the neighbours within the boundaries of the array. For this consider the following example if index is 1 then the left neighbor is only one element which is 0.
Thanks a lot
yields
The reason why
a[index-num_neighbor:index]does not work whenindex<num_neighboris because of slicing rules #3 and #4:Given
s[i:j]:So when
index=1, thena[index-num_neighbor:index] = a[-2:1] = a[10-2:1] = a[8:1] = [].