numpy 如果大于某个阈值则输出1,如果小于另一个阈值则输出0,如果在这些阈值之间则忽略

0ve6wy6x  于 2023-04-06  发布在  其他
关注(0)|答案(2)|浏览(155)

假设我有一个数组

arr = [0.1, 0.2, 0.3, 0.4, 0.5]

我有两个阈值threshold1=0.25和threshold2=0.35
我需要输出一个生成[0,0,1,1]的数组。如果数组arr中的value小于threshold1,则输出数组元素应为0,如果大于threshold2,则输出1。
我知道一个像output= [0 if x < threshold else 1 for x in arr]这样的一行代码,但是这会生成5个元素的输出,这是不正确的。在一行代码中正确的方法是什么?
我需要输出[0,0,1,1]。

cwxwcias

cwxwcias1#

您可以在列表解析中添加筛选条件:

arr = [0.1, 0.2, 0.3, 0.4, 0.5]

threshold1=0.25
threshold2=0.35

output= [0 if x < threshold1 else 1 for x in arr if x < threshold1 or x > threshold2]

print(output) # [0, 0, 1, 1]
ioekq8ef

ioekq8ef2#

另一种可能的解决方案:

[x for x in [0 if y < threshold1 else 
             1 if y > threshold2 else None for y in arr] if x is not None]

输出:

[0, 0, 1, 1]

相关问题