Skip to content Skip to sidebar Skip to footer

How To Threshold Values In Python Without If Statement (to Zero If Below Threshold, Same If Above)

I want to do an inline comparison without writing 'If statements' in Python. If the value meets the threshold condition, it should be unchanged. If it doesn't the value should be

Solution 1:

You need -

a = [1.5, 1.3, -1.4, -1.2]
positive_a_only = [i if i>0 else 0 for i in a]

print(positive_a_only)

Output

[1.5, 1.3, 0, 0]

This is known as a List Comprehension According to your input and expected output, this is a "pythonic" way to do this

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

You use case is kind of made for this :)

Solution 2:

It may worth looking at Numpy if you are working with numerical arrays.

import numpy as np

a = np.array([1.5, 1.3, -1.4, -1.2])
a[a < 0] = 0# [ 1.5  1.3  0.   0. ]

Solution 3:

The best answer I have found so far is to enumerate and loop through the array, using the python operator for the threshold or comparison logic.

The key is to multiply the index element by the logical comparison. e.g.

a = 1.5
a_positive = a * (a>0)
print(a)

Returns the value of 1.5 as expected, and returns 0 if a is negative.

Here's the example then with the full list:

a = [1.5, 1.3-1.4, -1.2]
for i, element inenumerate(a):
     a[i] = element*(element>0)

print(a)
[1.5, -0.0, -0.0]

Hope that helps someone!

Post a Comment for "How To Threshold Values In Python Without If Statement (to Zero If Below Threshold, Same If Above)"