在一个重置的一系列计数器中,找到Counter的起始索引 the,一个看起来像这样的数组: 值[0、0、1、2、3、4、5、0、1、2、3、4、5、6、0、0、1、2、3] 索引0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...

问题描述 投票:0回答:1
如果我搜索索引3,我想在再次重置该计数器之前获取该计数器的起点和端索引的索引,即2-6。

对于索引10,我想获得8-13。 对于索引16,我想获得16-18。

我如何在numpy中实现这一目标?
	
您可以通过以下内容来获得非壁球伸展的开始/结束坐标:

idx = np.nonzero(values == 0)[0] start = idx+1 end = np.r_[idx[1:]-1, len(values)-1] m = start<end indices = np.c_[start, end][m]

indices

python numpy
1个回答
0
投票
array([[ 2, 6], [ 8, 13], [16, 18]])

然后使用
searchsorted

(假设您仅通过非零件索引,否则您需要对输出的内容进行额外检查和说明):

indices[np.searchsorted(indices[:, 1], 2)]
输入:

values = np.array([0, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 0, 0, 1, 2, 3])

    

import numpy as np arr = np.array([0, 0, 1, 2, 3, 4,5, 0, 1, 2, 3, 4, 5, 6, 0, 0,1, 2, 3]) resets = np.where(arr == 0)[0] # Create an array of boundaries boundaries = np.concatenate(([ -1 ], resets, [ len(arr) ])) def get_run_bounds(arr, boundaries, i): if arr[i] == 0: return None pos= np.searchsorted(boundaries, i, side='right') start = boundaries[pos- 1] + 1 end = boundaries[pos] - 1 return (start, end) print("Index 3→",get_run_bounds(arr, boundaries, 3)) # waiting for(2, 6) print("Index 10 →", get_run_bounds(arr, boundaries, 10)) # (8, 13) print("Index 16 →", get_run_bounds(arr, boundaries, 16))# (16, 18)
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.