如果这是重复的,我很抱歉,但我没有找到这个问题的合适答案。
如果Python中有一个bytes对象,像这样:
b' \x00\x00\x00\x01\x00\x00\x00TEST\xa2~\x08A\x83\x11\xe3@\x05\x00\x00\x00\x03\x00\x00\x00TEST\x91\x9b\xd1?\ x1c\xaa,@'
它首先包含一定数量的整数(4 个字节),然后是一个 4 个字符的字符串,然后是一定数量的浮点数(4 个字节)。 此操作会重复一定次数,每次对应新的数据行。每行的格式是相同且已知的。在示例中,这是 2 行,每行 2 个整数、1 个字符串和 2 个浮点数。
我的问题是,是否有办法将这种数据直接转换为 pandas DataFrame。
我当前的方法是首先读取所有值(例如使用 struct.Struct.unpack)并将它们放入列表列表中。然而,这看起来相当慢,尤其是对于大量行。
这对我来说效果很好:
import numpy as np
import pandas as pd
data = b'\n\x00\x00\x00\x01\x00\x00\x00TEST\xa2~\x08A\x83\x11\xe3@\x05\x00\x00\x00\x03\x00\x00\x00TEST\x91\x9b\xd1?\x1c\xaa,@'
dtype = np.dtype([
('int1', np.int32),
('int2', np.int32),
('string', 'S4'),
('float1', np.float32),
('float2', np.float32),
])
structured_array = np.frombuffer(data, dtype=dtype)
df = pd.DataFrame(structured_array)
df['string'] = df['string'].str.decode('utf-8')
print(df)