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
509 views
in Technique[技术] by (71.8m points)

python - Convert NumPy array to 0 or 1 based on threshold

I have an array below:

a=np.array([0.1, 0.2, 0.3, 0.7, 0.8, 0.9])

What I want is to convert this vector to a binary vector based on a threshold. take threshold=0.5 as an example, element that greater than 0.5 convert to 1, otherwise 0.
The output vector should like this:

a_output = [0, 0, 0, 1, 1, 1]

How can I do this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

np.where

np.where(a > 0.5, 1, 0)
# array([0, 0, 0, 1, 1, 1])

Boolean basking with astype

(a > .5).astype(int)
# array([0, 0, 0, 1, 1, 1])

np.select

np.select([a <= .5, a>.5], [np.zeros_like(a), np.ones_like(a)])
# array([ 0.,  0.,  0.,  1.,  1.,  1.])

Special case: np.round

This is the best solution if your array values are floating values between 0 and 1 and your threshold is 0.5.

a.round()
# array([0., 0., 0., 1., 1., 1.])

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

...