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

时间:2011-09-16 09:22:24

标签: python numpy

我想获取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,则左邻居只有一个元素为0。

非常感谢

4 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:3)

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

a[index-num_neighbor:index]slicing rules #3 and #4而导致index<num_neighbor失效的原因:

鉴于s[i:j]

  

如果i或j为负数,则索引相对于字符串的结尾:   len(s)+ i或len(s)+ j被替换。

     

从i到j的s片被定义为具有的项目序列   索引k使得i <= k <1。学家如果i或j大于len(s),请使用   镜片)。如果省略i或None,则使用0.如果省略j或None,请使用   镜片)。如果i大于或等于j,则切片为空。

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

答案 2 :(得分:0)

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]

答案 3 :(得分:0)

我想出的方法包括将数组切成薄片,然后根据需要填充以填充边界值。

取自here

def surrounding(x, idx, radius=1, fill=0):
""" 
Gets surrounding elements from a numpy array 

Parameters: 
x (ndarray of rank N): Input array
idx (N-Dimensional Index): The index at which to get surrounding elements. If None is specified for a particular axis,
    the entire axis is returned.
radius (array-like of rank N or scalar): The radius across each axis. If None is specified for a particular axis, 
    the entire axis is returned.
fill (scalar or None): The value to fill the array for indices that are out-of-bounds.
    If value is None, only the surrounding indices that are within the original array are returned.

Returns: 
ndarray: The surrounding elements at the specified index
"""

assert len(idx) == len(x.shape)

if np.isscalar(radius): radius = tuple([radius for i in range(len(x.shape))])

slices = []
paddings = []
for axis in range(len(x.shape)):
    if idx[axis] is None or radius[axis] is None:
        slices.append(slice(0, x.shape[axis]))
        paddings.append((0, 0))
        continue

    r = radius[axis]
    l = idx[axis] - r 
    r = idx[axis] + r

    pl = 0 if l > 0 else abs(l)
    pr = 0 if r < x.shape[axis] else r - x.shape[axis] + 1

    slices.append(slice(max(0, l), min(x.shape[axis], r+1)))
    paddings.append((pl, pr))

if fill is None: return x[slices]
return np.pad(x[slices], paddings, 'constant', constant_values=fill)