Values less than a threshold in Python

Viewed 88

I have an array, sigma. If any element of sigma is less than threshold, then the value of the specific element is equal to the threshold. The current and expected outputs are presented.

import numpy as np

sigma = np.array([[ 0.02109   ],
                  [ 0.01651925],
                  [ 0.02109   ],
                  [ 0.02109   ],
                  [ -0.009   ]])

threshold = 0.010545

for i in range(0, len(sigma)):
    if(sigma[i] <= threshold):
        sigma[i] == threshold

print([sigma])

The current output is

[array([[ 0.02109   ],
       [ 0.01651925],
       [ 0.02109   ],
       [ 0.02109   ],
       [-0.009     ]])]

The expected output is

[array([[0.02109   ],
       [0.01651925],
       [0.02109   ],
       [0.02109   ],
       [0.010545  ]])]
3 Answers

It is a good start you are doing a threshold. In fact, NumPy has a good function to help you perform faster. That is np.clip.

import numpy as np

sigma = np.array([[ 0.02109 ],
                  [ 0.01651925],
                  [ 0.02109   ],
                  [ 0.02109   ],
                  [ -0.009   ]])

threshold = 0.010545

np.clip(sigma, threshold, np.inf)

Output

array([[0.02109   ],
       [0.01651925],
       [0.02109   ],
       [0.02109   ],
       [0.010545  ]])

np.clip is actually a function that limits your array within a boundary (with a minimum and maximum value). So, if you are performing array elementwise operation, you can use np.clip to make sure all the elements stay within the boundary.

There is a typo in the code. You need to assign instead of comparing.

for i in range(0,len(sigma)):
    if(sigma[i]<=threshold):
        sigma[i]=threshold

You just have a typo when assigning the value of the array:

for i in range(0, len(sigma)):
    if(sigma[i] <= threshold):
        sigma[i] == threshold
Related