2

I have array:

x = np.array([1, 41, 32, 2, -8, 0, -97, 11])

If x[i] > 0, x[i] = 1

If x[i] < 0, x[i] = -1

If x[i] == 0, x[i] = 0

So expected output:

x = np.array([1, 1, 1, 1, -1, 0, -1, 1])

Is there a way to do this with a one liner in numpy without any loops? I wanted to use np.where but it only takes 2 conditions whereas I have 3. Thanks.

2 Answers 2

1

You can use np.select for multiple conditions:

np.select([x==0,x>0,x<0],[0,1,-1])
# array([ 1,  1,  1,  1, -1,  0, -1,  1])

Or for just two conditions you could also do it in-place as:

x[x>0] = 1
x[x<0] = -1

print(x)
# array([ 1,  1,  1,  1, -1,  0, -1,  1])

Though probably the simplest here is np.clip:

np.clip(x,-1,1)
# array([ 1,  1,  1,  1, -1,  0, -1,  1])
Sign up to request clarification or add additional context in comments.

Comments

1

Indeed it takes 3 parameters:

x = np.where(x > 0 , x, 1)

1 Comment

Sir, have you tried using the equation you posted to get my expected output?

Your Answer

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