1

I have one numpy array that stores the thresholds and another array that store some values. I want these last values to be less or equal of the corresponding thresholds. In particular, if a value is greater than its corresponding threshould I should change it with the thresholds.

The following example gives exactly what I want but I'm wondering if exist a better way to implement it or if already exist a numpy method (that I searched for but that I didn't find) to do it.

In [1]: import numpy as np

In [2]: a = np.random.rand(10)

In [3]: a
Out[3]: 
array([0.38331068, 0.32042463, 0.89980916, 0.86472908, 0.10812789,
       0.35855107, 0.09916983, 0.55710449, 0.38591185, 0.70798023])

In [4]: t = np.array([0.95, 0.9, 0.8, 0.75, 0.7, 0.65, 0.6, 0.55, 0.5, 0.45])

In [5]: mask = a > t

In [6]: a[mask] = t[mask]

In [7]: a
Out[7]: 
array([0.38331068, 0.32042463, 0.8       , 0.75      , 0.10812789,
       0.35855107, 0.09916983, 0.55      , 0.38591185, 0.45      ])

1 Answer 1

1

You can use np.clip:

>>> np.clip(a,a_min=None,a_max=t)
array([0.38331068, 0.32042463, 0.8       , 0.75      , 0.10812789,
       0.35855107, 0.09916983, 0.55      , 0.38591185, 0.45      ])
Sign up to request clarification or add additional context in comments.

4 Comments

This means that if I also have a lower threshold I could do np.clip(a,a_min=t_min,a_max=t_max) where t_min contains the lower thresholds and t_max the higher thresholds?
Exactly, I think it's along the lines of what you're looking for
Usually, I wait for 24h before accepting an answer but I don't think that this would be the case.
Do as you wish! Glad I could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.