简体   繁体   中英

How to replace all elements of Python NumPy Array that are greater than a several values?

I know that I can replace all elements of Python NumPy Array that are greater than some value:

np.putmask(A, A>0.5, 5)

Where A>0.5 is the threshold and 5 the new replacement. However, how can I do it for more conditions? for example for:

if x.all <0:
    return 00.1
elif x.all >0:
    return 1

Where x is an array. I tried to:

np.putmask(x, x<0, 00.1)

and

np.putmask(x, x>0, 1)

However, I would like to do it in a single line. Any idea of how to do this type of replacements in just a single line with putmask or any other method?

Are you looking for dual np.where ie

A = np.array([0,1,2,3,1,-5,-6,-7])

k = np.where(A>0,1,np.where(A<0,0.01,A))

Or you can use np.select for multiple conditions .

k = np.select([A>0,A<0],[1,.01],A)

Ouptut :

[ 0.    1.    1.    1.    1.    0.01  0.01  0.01]

You can create masks (logical arrays) of each condition, and then apply all masks.

# Create masks
mask1 = (x < 0)
mask2 = (x > 0)
# Apply masks
x[mask1] = 0.1
x[mask2] = 1

If you really need it on a single line:

mask1 = (x < 0); mask2 = (x > 0); x[mask1] = 0.1; x[mask2] = 1

You may also use the putmask function as in your example code:

mask1 = (x < 0); mask2 = (x > 0); np.putmask(x, mask1, 00.1); np.putmask(x, mask2, 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM