[英]Find the value of an index and the n-closest neighbors in a NumPy array
I wondered if anyone could tell me how to find the index of a number and the indexes of the n-closest neighbors in a NumPy
array.我想知道是否有人可以告诉我如何在NumPy
数组中找到数字的索引和 n-最近邻居的索引。
For example, In this array, I would like to find the index of the value 87
, and its four closest neighbors 86
, 88
to the left and 78
, 43
to the right.例如,在这个数组中,我想找到值87
的索引,以及它左边的四个最近邻居86
、 88
和右边的78
、 43
。
a = np.random.randint(1,101,15)
array([79, 86, 88, 87, 78, 43, 57])
If you want to change the values from time to time, although this would be expensive for large arrays, should do the trick:如果您想不时更改值,尽管这对于大型 arrays 来说会很昂贵,但应该这样做:
a = np.array([79, 86, 88, 87, 78, 43, 57])
number = 87
n_nearest = 4
index = np.where(a == number)[0][0] # np.where returns (array([3]),)
a = a[max(0, index - n_nearest // 2):index + n_nearest // 2 + 1]
nearests = np.delete(a, n_nearest // 2)
print(nearests)
Output: [86 88 78 43]
Output: [86 88 78 43]
First, find the index of the value you get the neighbors (may not work with duplicate values though).首先,找到您获得邻居的值的索引(尽管可能不适用于重复值)。
You should do max(0, index - 2)
in case of the value you want may be at the beginning of array (position 0 or 1).如果您想要的值可能位于数组的开头(位置 0 或 1),则应该执行max(0, index - 2)
)。
Then, delete the number from the result.然后,从结果中删除数字。 The rest of it will be the neighbors you want.它的 rest 将是您想要的邻居。
I had a go at it, with the caveat that I'm not hugely experienced with python or numpy - only a couple of months我有一个 go ,但需要注意的是,我对 python 或 numpy 的经验并不丰富 - 只有几个月
(...so I'd also look for someone else to chip in a much cleaner/simpler/better method!) (......所以我也会寻找其他人来使用更清洁/更简单/更好的方法!)
from functools import reduce
import operator
a = np.array([5, 10, 15, 12, 88, 86, 5, 87, 1,2,3, 87,1,2,3])
look_for = 87
# find indicies where a == 87:
np.nonzero(a == look_for)
# get as interable
np.nonzero(a == look_for)[0]
# put into list comprehension with the delta in indicies you want and the values
# from above inside 'range' to generate a range of values b/w index-delta:index+delta,
# then wrap it into a list to generate the list from the range iterator:
delta = 2
[list(range(i-delta,i+delta+1)) for i in np.nonzero(a==87)[0]]
# above gives you a list of lists, need to flatten into a single list
reduce(operator.concat, [list(range(i-delta,i+delta+1)) for i in np.nonzero(a==87)[0]])
# want only unique values, so one way is to turn above into a set
set(reduce(operator.concat, [list(range(i-delta,i+delta+1)) for i in np.nonzero(a==87)[0]]))
# the above gives you a set with all the indicies, with only unique values.
# one remaning problem is it still could have values < 0 or > a.size, so
# you'd now want to wrap it all into another list comprehension to get rid of
# any values < 0 or > a.size
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.