如何在考虑边界的情况下获取numpy数组中的相邻元素?

2024-05-14 17:40:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到numpy数组中某个元素的邻居。让我们考虑下面的例子

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

所以我想指定位置5,并从两边找三个邻居。可以做到的

   index = 5
   num_neighbor=3
   left = a[index-num_neighbor:index]
   right= a[num_neighbor+1:num_neighbor+index+1]

上面的代码不考虑边界。。。我要让邻居在阵列的边界内。为此,请考虑下面的示例:如果index为1,则left neighbor仅是一个0元素。

非常感谢


Tags: 代码rightnumpy元素示例index数组array
3条回答

Python为您处理边界:

>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[-100 : 1000]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[-100:3]
[0, 1, 2]
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)

收益率

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

index<num_neighbora[index-num_neighbor:index]不起作用的原因是slicing rules #3 and #4

给定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.

所以当index=1,然后a[index-num_neighbor:index] = a[-2:1] = a[10-2:1] = a[8:1] = []

left = a[max(0,index-num_neighbor):index]

相关问题 更多 >

    热门问题