Values less than a threshold in Python

Question:

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   ]])]
Asked By: Wiz123

||

Answers:

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
Answered By: Himanshuman

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.

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

threshold = 0.010545

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

Output

Out[4]:
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.

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
Answered By: Ameni Ben Amor
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.