在Python中将字节串转换为浮点数

时间:2016-09-09 14:12:02

标签: python pandas byte

我正在使用Pandas来处理我的数据。我的脚本的第一步是将一列字节转换为浮点列表。我的脚本正在运行,但耗时太长。关于如何加快速度的任何建议??

def byte_to_hex(byte_str):
    array = ["%02X" % ord(chr(x)) for x in byte_str]
    return array

for index, row in enumerate(data[column].values):
    row_new = []
    row = byte_to_hex(row)
    stop = len(row)
    for i in range(4, stop, 4):
        sample = "".join(row[i:i + 4])
        row_new.append(struct.unpack('!f', bytes.fromhex(sample))[0])

例:
    B'\ X00 \ X00 \ X00 \ x1cB \ X80 \ X1F \ XFCB \ X80 \ X1F \ XFCB \ x80w \ xc8Bz ​​\ XA1 \ x97B \ X80 \ X1F \ XFCB} LZB \ X80 \ X1F \ xfcBz \ XA1 \ x97Bz \ xcaoB \ x803 \ xf5B} \ XC5 \ x84B \ x80w \ xc8B} \固定的\ xdbB \ X80 \ X1F \ XFCB} \ XC5 \ x84B} LZB \ X80 \ X1F \ XFCB}#\ xe9B} \固定的\ xdbB} \ XC5 \ x84B \ x803 \ xf5B \ X80 \ X1F \ XFCB} \ XC5 \ x84B \ x803 \ xf5B \ x803 \ xf5Bx \ XEF \ TB \ X81 \ XC4 \ XDF \ 0x7F部分\ XFF \ XFF \ XFF'

[64.06246948242188, 64.06246948242188, 64.23394775390625, 62.65780258178711, 64.06246948242188, 63.324562072753906, 64.06246948242188, 62.65780258178711, 62.697689056396484, 64.10147857666016, 63.44288635253906, 64.23394775390625, 63.48228073120117, 64.06246948242188, 63.44288635253906, 63.324562072753906, 64.06246948242188, 63.28506851196289, 63.48228073120117, 63.44288635253906, 64.10147857666016, 64.06246948242188, 63.44288635253906, 64.10147857666016, 64.10147857666016]

非常感谢任何帮助:)

1 个答案:

答案 0 :(得分:2)

我认为您正在寻找Struct

import struct

struct.pack('f', 3.14)
OUT: b'\xdb\x0'

struct.unpack('f', b'\xdb\x0fI@')
OUT: (3.1415927410125732,)

struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
OUT: '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'