Converting float column values (both whole part and decimal part) into binary in python

0

I want to convert all values in the columns of my dataset into binary representation of 20 bits, and create a list of those values.

ex. 0.1234 as 00000001001000110100 1.2002 as 00010010000000000010 and so on

I tried doing it for a number, but for whole dataset, I’m unable to do so.

#let one of the values to be converted is 'v1'
v1 = 12.569
whole, dec = str(v1).split(".")
dig1 = [int(d) for d in str(whole)]
dig2=[int(e) for e in str(dec)]
res = dig1+dig2
newl=[]
for i in res:
    newl.append(bin(int(i))[2:].zfill(4))
newl
for m in newl:
    print(m, end="")

It results in: 00010010010101101001

But for a whole column (or multiple columns) of my dataset, I’m unable to do so

df1_ = [0.4, 0.3, 0.2, 0.5, 0.6]
newl=[]
enc1=[]
for vals in df1_:
    whole, dec = str(vals).split(".")
    #whole = int(whole)
    dig = [int(d) for d in str(whole)]
    dig2=[int(e) for e in str(dec)]
    res = dig+dig2
    for i in res:
        #l = 4
        newl.append(bin(int(i))[2:].zfill(4))
    s = [str(y) for y in newl]
    res1 = int("".join(s))
    enc1.append(res1)
   
enc1

The output is as follows: [100, 10000000011, 1000000001100000010, 100000000110000001000000101, 10000000011000000100000010100000110]

But I want output as: [00000100,00000011,00000010,00000101,00000110]

Looks like a good place to use a function. Enclose your first attempt as a function and then call it in a loop for each of the values you want.

def float2bin(n):
    whole, dec = str(n).split(".")
    dig1 = [int(d) for d in str(whole)]
    dig2 = [int(e) for e in str(dec)]
    res = dig1 + dig2
    newl = [bin(int(i))[2:].zfill(4) for i in res]
    s = "".join(newl)
    return s

df1_ = [0.4, 0.3, 0.2, 0.5, 0.6]
ans = [float2bin(n) for n in df1_]
print(ans)
['00000100', '00000011', '00000010', '00000101', '00000110']
1 Like