在python中查找numpy数组中具有条件的第一个元素的索引

2024-10-04 01:37:26 发布

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

我试图找到第一个元素的索引大于阈值,如下所示:

index = 0
while timeStamps[index] < self.stopCount and index < len(timeStamps):
    index += 1

这能在一个班轮吗?我发现:

index = next((x for x in timeStamps if x <= self.stopCount), 0)

我不知道这个表达式做什么,它似乎总是返回0。。。有人能指出错误并解释一下表达式吗?你知道吗


Tags: andinself元素forindexlenif
3条回答

这个班轮行得通

sample_array = np.array([10,11,12,13,21,200,1,2])

# oneliner
print(sum(np.cumsum(arr>threshold)==0))

np.cumsum(sample_array>threshold)==0)将具有值0,直到元素大于阈值

另一种选择是使用^{}(参见this post for details)。所以你的代码会变成

(timeStamps > self.stopCount).argmax()

需要注意的是,如果条件从未满足,argmax将返回0。你知道吗

我会这样做:

import numpy as np

threshold = 20

sample_array = np.array([10,11,12,13,21,200,1,2])

idx = np.array([np.where(sample_array > threshold)]).min()
print(idx)
#4

相关问题 更多 >