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?
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.
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.
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] .
np.where
np.where(a > 0.5, 1, 0) # array([0, 0, 0, 1, 1, 1])
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.])
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.])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With