我正在使用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 \ xBBz \ x803 \ xf5B} \ xc5 \ x84B \ x80w \ xc8B} \ xed \ xdbB \ x80 \ x1f \ xfcB} \ xc5 \ x84B} LZB \ x80 \ x1f \ xfcB}#\ xe9B} \ xed \ xdbB} \ xc5 \ x84B \ x803 \ xf5B \ x80 \ x1f \ xfcB} \ xc5 \ x84B \ x803 \ xf5B \ x803 \ xf5Bx \ xef \ tB \ x81 \ xc4 \ xdf \ x7f \ 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]


非常感谢您的帮助:)

最佳答案

我认为您正在寻找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@'

关于python - 在Python中将字节字符串转换为浮点数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39413600/

10-09 08:03