Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 912
freefrog Avatar asked Sep 14 '17 08:09

freefrog


People also ask

Do NumPy arrays start at 0 or 1?

Access Array ElementsThe indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do I convert a NumPy array to integer?

To convert numpy float to int array in Python, use the np. astype() function. The np. astype() function takes an array of float values and converts it into an integer array.

How do I create a NumPy array of zeros and ones?

To initialize your NumPy array with zeros, use the function np. zeros(shape) where shape is a tuple that defines the shape of your desired array. For example, np. zeros((3,)) defines a one-dimensional array with three “0” elements, i.e., [0 0 0] .


Video Answer


1 Answers

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.]) 
like image 148
cs95 Avatar answered Sep 27 '22 18:09

cs95