将无分隔字节转换为pandas DataFrame
抱歉如果这个问题重复了,但我没有找到合适的答案来解决这个问题。
假设你在Python中有一个字节对象,像这样:
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,@'
这个字节对象首先包含了一定数量的整数(每个4个字节),然后是一个包含4个字符的字符串,接着是一定数量的浮点数(每个4个字节)。这个结构会重复多次,每次对应一行新的数据。每一行的格式都是一样的,且是已知的。在这个例子中,有2行数据,每行包含2个整数、1个字符串和2个浮点数。
我的问题是,是否有办法直接将这种数据转换成pandas的DataFrame。
我现在的做法是先读取所有的值(比如用struct.Struct.unpack),然后把它们放在一个列表的列表里。不过,这样的做法似乎比较慢,尤其是当行数很多的时候。
1 个回答
0
这段代码对我来说运行得很好:
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)
而且给我输出了以下内容:
int1 int2 string float1 float2
0 10 1 TEST 8.530916 7.095888
1 5 3 TEST 1.637560 2.697883