6

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?

1
  • To put actual integer values in the array (as opposed to float 1.0) you have switch to a structured array, or just put the binary values in a separate array. Commented Jan 16, 2017 at 17:27

1 Answer 1

5

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.]])
Sign up to request clarification or add additional context in comments.

3 Comments

To be even more precise: The result of a[:,1]>1.5 is a boolean array, but the assignment converts it back to float.
@Trilarion Right. Added that.
Yes, it's a boolean array. For instance a = a[:, 1]>1.5 results in [False False False True False False]. But as I need to do math with these values I need them to be integers. But a[:, 1] = a[:, 1]>1.5 works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.