1

I have this python code:

    for i, num in enumerate(num_arr):
        if num > threshold:
            num_arr[i] = threshold

'num_arr' is a simple array filled with integers, 'threshold' may vary from 10 to 100,000. Is there any faster way to achieve the same result? bitwise operation or something of that sort?

Dan Shorla Ki
  • 115
  • 1
  • 8

1 Answers1

1

You can use .clip(..) [numpy-doc] for that. For example:

num_arr = num_arr.clip(max=threshold)

For example:

>>> a
array([14, 25,  7, 12,  2])
>>> a.clip(max=10)
array([10, 10,  7, 10,  2])
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555