Gravity Mass
Gravity Mass

Reputation: 605

Convert Byte type into float

I have a numpy array:

import numpy as np
Boolval = np.array([b'false',b'true',b'false',b'false',b'false',b'false',b'false',b'false'])

I am trying to convert each value into the entire array with value 0 or 1 (e.g. [0, 1, 0, 0, 0, 0, 0]).

I tried the following:

import struct
print(struct.unpack('f',Boolval))

It throws an error: struct.error: unpack requires a buffer of 4 bytes

I tried with just one value,

print(struct.unpack("f", Boolval[1]))

It gives the value of (7.24431922380234e+22,). Not 1 or 0.

Upvotes: 1

Views: 224

Answers (2)

hpaulj
hpaulj

Reputation: 231325

In [253]: Boolval = np.where([0,1,0,0,1,0,1],b'true',b'false')                                         
In [254]: Boolval                             # the repr display                                                         
Out[254]: 
array([b'false', b'true', b'false', b'false', b'true', b'false', b'true'],
      dtype='|S5')
In [255]: print(Boolval)                 # the str display                                                              
[b'false' b'true' b'false' b'false' b'true' b'false' b'true']

In [256]: Boolval!=b'false'                                                                            
Out[256]: array([False,  True, False, False,  True, False,  True])
In [257]: Boolval==b'true'                                                                             
Out[257]: array([False,  True, False, False,  True, False,  True])

We can convert it to boolean array with a comparison to a bytestring:

In [256]: Boolval!=b'false'                                                                            
Out[256]: array([False,  True, False, False,  True, False,  True])
In [257]: Boolval==b'true'                                                                             
Out[257]: array([False,  True, False, False,  True, False,  True])

and to an integer array with a astype conversion:

In [258]: (Boolval!=b'false').astype(int)                                                              
Out[258]: array([0, 1, 0, 0, 1, 0, 1])

In [259]: np.where(Boolval==b'true')                                                                   
Out[259]: (array([1, 4, 6]),)

And the list comprehension approach:

In [260]: [int(b == b'true') for b in Boolval]                                                         
Out[260]: [0, 1, 0, 0, 1, 0, 1]

If we start with a list, the list comprehension is often faster. But starting with an array it is likely to be slower. Though here the sample is small, and the string equality test isn't nearly as fast as numeric operations.

Upvotes: 2

Selcuk
Selcuk

Reputation: 59164

They are not byte values, they are binary strings. Try something like

>>> [int(b == b'true') for b in Boolval]
[0, 1, 0, 0, 0, 0, 0, 0, 0]

This will check if the item is equal to b'true' and convert the truth value (True or False) to an int.

Upvotes: 4

Related Questions