对于索引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
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)