Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Are you looking for dual np.where i.e

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...