Replacing values in numpy array based on multiple conditions without using any loops

Viewed 153

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

Indeed it takes 3 parameters:

x = np.where(x > 0 , x, 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])
Related