如何在考虑边界的情况下获取numpy数组中的相邻元素? [英] how to get the neighboring elements in a numpy array with taking boundaries into account?

查看:189
本文介绍了如何在考虑边界的情况下获取numpy数组中的相邻元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取numpy数组中某些元素的邻居.让我们考虑以下示例

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

所以我想指定位置5,并希望从双方得到三个邻居.可以做到

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]

上面的代码没有考虑边界...我希望我在数组的边界内得到邻居.为此,请考虑以下示例,如果index为1,则左邻居仅是一个元素,该元素为0.

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.

非常感谢

推荐答案

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]不起作用的原因是由于


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

给出s[i:j]:

如果i或j为负,则索引相对于字符串的结尾: len(s)+ i或len(s)+ 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.

从i到j的s切片被定义为具有 索引k使得i< = k< j.如果i或j大于len,请使用 镜片).如果省略i或无,请使用0.如果省略j或无,请使用 镜片).如果i大于或等于j,则切片为空.

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] = [].

这篇关于如何在考虑边界的情况下获取numpy数组中的相邻元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆