确定信号高于预定界限的时间

2024-10-02 04:32:03 发布

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

我有两个大列表ty,我想以一种性能的方式确定y中的数据超过预定义的limit,即>=limit的时间和长度。你知道吗

该问题可用以下示例数据说明:

t = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
y = [8,6,4,2,0,2,4,6,8,6,4,2,0,2,4,6,8]
limit = 4

enter image description here

在本例中,代码应返回以下列表:

t_exceedance_start = [0,6,14]
t_how_long_above_limit = [2,4,2]

我希望这可以在Numpy中非常优雅地实现,但没有发现如何实现。你知道吗

如有任何建议,我们将不胜感激。你知道吗


Tags: 数据代码numpy示例列表方式时间性能
1条回答
网友
1楼 · 发布于 2024-10-02 04:32:03

这里有一个矢量化的方法,利用布尔来提高性能效率-

# Get array versions if aren't already
y = np.asarray(y)
t = np.asarray(t)

# Get mask of thresholded y with boundaries of False on either sides.
# The intention is to use one-off shifted comparison to catch the
# boundaries of each island of thresholed True values (done in next step).
# Those appended False values act as triggers to catch the start of 
# first island and end of last island.
mask = np.concatenate(( [False], y>=limit, [False] ))
idx = np.flatnonzero(mask[1:] != mask[:-1])

# The starting indices for each island would be the indices at steps of 2.
# The ending indices would be steps of 2 as well starting from first index.
# Thus, get the island lengths by simply differencing between start and ends.
starts = idx[::2]
ends =   idx[1::2] - 1
lens = ends - starts

# Get starts, ends, lengths according to t times
start_times = t[starts]
end_times = t[ends]
len_times = end_times - start_times

相关问题 更多 >

    热门问题