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

时间:2021-03-14 21:41:26

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:

现在我想将浮点值从第二列(数组[:,1]中的那些)转换为单位二进制值,表示为1或0整数。我有阈值,我想用它作为逻辑0和逻辑1之间的限制。假设它是1.5。转换后,数组应如下所示:

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

How do I do that with the least effort?

如何以最少的努力做到这一点?

1 个解决方案

#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.

将第二列与阈值进行比较,该阈值将是一个布尔数组,然后将其分配回第二列。在分配之前,赋值会将其向上转换为浮动数据。得到的第二列仍然是浮点数,但是因为它需要在那里维护数据类型为0和1。

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.]])

#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.

将第二列与阈值进行比较,该阈值将是一个布尔数组,然后将其分配回第二列。在分配之前,赋值会将其向上转换为浮动数据。得到的第二列仍然是浮点数,但是因为它需要在那里维护数据类型为0和1。

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.]])