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

2024-06-02 08:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我用熊猫来处理我的数据。我的脚本的第一步是将一列字节字符串转换成一系列浮点数。我的剧本很管用,但时间太长了。关于如何加快速度有什么建议吗??在

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\x00\x00\x1cB\x80\x1f\xfcB\x80\x1f\xfcB\x80\x1f\xfcB\x80w\xc8Bz\xa1\x97B\x80\x1f\XFB\x80\x1f\LZB\x80\x1f\xfcBz\xa1\x97Bz\xcaoB\X8003\xf5B}\XC55\x84B\x80w\xc8B\X8B\X8B\X8B\X8B\X8\X8\XBB\x80\x80\x1f\xfcB\X85\x1f\xfcB \X5\X4B}LZB\x80\x80#\xe9B}\xex\xdbB}\xc5\x84B\x803\xf5B\x80\x1f\xfcB}\xc5\x84B\x803\xf5B\x803\xf5Bx\xef\tB\x81\xc4\xdf\x7f\xff\xff\xff'

^{pr2}$

非常感谢您的帮助:)


Tags: toinforbyterowhexx00xff
1条回答
网友
1楼 · 发布于 2024-06-02 08:32:06

我想你在找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@'

相关问题 更多 >