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
如果要不时更改这些值,尽管这对于大型阵列来说成本很高,但应该执行以下操作:
输出:
[86 88 78 43]
首先,找到相邻值的索引(但可能不适用于重复值)。你知道吗
你应该做
max(0, index - 2)
,如果你想要的值可能在数组的开头(位置0或1)。你知道吗然后,从结果中删除数字。剩下的将是你想要的邻居。你知道吗
我试过了,但要提醒的是,我对python或numpy的经验并不丰富——只有几个月
(…所以我也会找其他人来用一种更干净/更简单/更好的方法!)
相关问题 更多 >
编程相关推荐