1

I have a 2d numpy array of integers, and now I want to change all the elements greater than 5 to 5.
For example,

[[2, 6],
 [7, 3]]

to

[[2, 5],
 [5, 3]]

Now, my current approach is to access all the elements using two for loops and then checking if each element is greater then 5, like this:

h, w = arr.shape[:2]
for x in range(h):
    for y in range(w):
        if arr[x,y] > 5:
            arr[x,y] = 5

Is there any more pythonic approach for doing this?

0

1 Answer 1

3

Use np.clip() It can clip both on lower and upper value. We just pass None as lower value, to clip only on upper one.

>>> import numpy as np
>>> arr = np.array([[2, 6], [7, 3]])
>>> arr
array([[2, 6],
       [7, 3]])
>>> np.clip(arr, None, 5)
array([[2, 5],
       [5, 3]])
>>>
Sign up to request clarification or add additional context in comments.

Comments

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.