Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy array with floats to binary (0 or 1 integers)

I have an input array that looks like this:

  [[  0.    1. ]
   [ 10.    0.4]
   [ 20.    1.4]
   [ 30.    3. ]
   [ 40.    1.1]
   [ 50.    0.7]]

Now I'd like to convert the float values from the second column (the ones in array[:, 1]) to single bit binary values represented as 1 or 0 integers. I have threshold value that I'd like to use as a limit between logical 0 and logical 1. Let's say it is 1.5. After the conversion the array should look like this:

  [[  0.    0 ]
   [ 10.    0]
   [ 20.    0]
   [ 30.    1]
   [ 40.    0]
   [ 50.    0]]

How do I do that with the least effort?

like image 213
ThoWe Avatar asked Jan 16 '17 08:01

ThoWe


1 Answers

Compare the second column against the threshold, which would be a boolean array and then assign it back to the second column. The assignment would upcast it to float data before assigning back. The resultant second column would still be float, but as 0s and 1s as it needs to maintain the datatype there.

Thus, simply do -

a[:,1] = a[:,1]>1.5

Sample run -

In [47]: a
Out[47]: 
array([[  0. ,   1. ],
       [ 10. ,   0.4],
       [ 20. ,   1.4],
       [ 30. ,   3. ],
       [ 40. ,   1.1],
       [ 50. ,   0.7]])

In [48]: a[:,1] = a[:,1]>1.5

In [49]: a
Out[49]: 
array([[  0.,   0.],
       [ 10.,   0.],
       [ 20.,   0.],
       [ 30.,   1.],
       [ 40.,   0.],
       [ 50.,   0.]])
like image 111
Divakar Avatar answered Sep 20 '22 03:09

Divakar