在NumPy数组中查找索引和nclosest邻居的值

2024-04-25 21:34:02 发布

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

我想知道是否有人能告诉我如何在NumPy数组中找到一个数的索引和n个最近邻居的索引。你知道吗

例如,在这个数组中,我想找到值87的索引,它的四个最近邻居86,左边88,右边78,右边43。你知道吗

a = np.random.randint(1,101,15)
array([79, 86, 88, 87, 78, 43, 57])

Tags: numpynprandom数组arrayrandint
2条回答

如果要不时更改这些值,尽管这对于大型阵列来说成本很高,但应该执行以下操作:

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)

输出:[86 88 78 43]

首先,找到相邻值的索引(但可能不适用于重复值)。你知道吗

你应该做max(0, index - 2),如果你想要的值可能在数组的开头(位置0或1)。你知道吗

然后,从结果中删除数字。剩下的将是你想要的邻居。你知道吗

我试过了,但要提醒的是,我对python或numpy的经验并不丰富——只有几个月

(…所以我也会找其他人来用一种更干净/更简单/更好的方法!)

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

相关问题 更多 >