0

Is it possible to compute the following using single where condition in Python. I'm unable to do that.

x = np.arange(10)

If an element of x is smaller than 3, replace it with 3. And if an element of x is bigger than 7, replace it with 7.

My attempt is as follows, however I'm wondering if it could be done in a single line of code

x= np.where(x<3 ,3,x) x = np.where(x>7,7,x)

Sorry, if it seems very basic. But I have just started with numpy

1
  • Simply use numpy.clip(). Commented Jun 24, 2017 at 7:50

3 Answers 3

1

You can do it in a single line using numpy.clip()

x = np.arange(10)
np.clip(x, 3, 7)
print(x)

#[3, 3, 3, 3, 4, 5, 6, 7, 7, 7]
Sign up to request clarification or add additional context in comments.

Comments

0

use numpy.clip()

In [115]: a = np.arange(10)

In [116]: np.clip(a, 3, 7)
Out[116]: array([3, 3, 3, 3, 4, 5, 6, 7, 7, 7])

Comments

-1
x= np.where(x<3, 3, np.where(x>7, 7, x))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.