Output 1 if greater than certain threshold and 0 less than another threshold and ignore if in between these threshold
Question:
Assume I have an array
arr = [0.1, 0.2, 0.3, 0.4, 0.5]
I have two thresholds threshold1=0.25 and threshold2=0.35
I need to output an array which generates [0, 0, 1, 1]. If value in array arr is less than threshold1, then output array element should be 0 and if greater than threshold2, it should output 1.
I know a one liner code like output= [0 if x < threshold else 1 for x in arr]
but this generates 5 element output and is not correct. What is the correct way of doing this in one line?
I am expecting output [0, 0, 1, 1].
Answers:
You can add filter condition in a list comprehension:
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]
Another possible solution:
[x for x in [0 if y < threshold1 else
1 if y > threshold2 else None for y in arr] if x is not None]
Output:
[0, 0, 1, 1]
Assume I have an array
arr = [0.1, 0.2, 0.3, 0.4, 0.5]
I have two thresholds threshold1=0.25 and threshold2=0.35
I need to output an array which generates [0, 0, 1, 1]. If value in array arr is less than threshold1, then output array element should be 0 and if greater than threshold2, it should output 1.
I know a one liner code like output= [0 if x < threshold else 1 for x in arr]
but this generates 5 element output and is not correct. What is the correct way of doing this in one line?
I am expecting output [0, 0, 1, 1].
You can add filter condition in a list comprehension:
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]
Another possible solution:
[x for x in [0 if y < threshold1 else
1 if y > threshold2 else None for y in arr] if x is not None]
Output:
[0, 0, 1, 1]