kas*_*rhj 15 python numpy pandas
我有一些二进制数据,我想知道如何将其加载到pandas中.
我可以以某种方式加载它指定它所在的格式,以及调用各列?
编辑:
格式是
int, int, int, float, int, int[256]
Run Code Online (Sandbox Code Playgroud)
每个逗号分隔代表数据中的一列,即最后256个整数是一列.
mow*_*wen 22
即使这是一个老问题,我也想知道同样的事情,我没有看到我喜欢的解决方案.
使用Python读取二进制数据时,我发现numpy.fromfile或者numpy.fromstring比使用Python结构模块快得多.只要数据格式是常量并且可以使用numpy数据类型object(numpy.dtype)来描述,具有混合类型的二进制数据可以使用上述方法有效地读入numpy数组.
import numpy as np
import pandas as pd
# Create a dtype with the binary data format and the desired column names
dt = np.dtype([('a', 'i4'), ('b', 'i4'), ('c', 'i4'), ('d', 'f4'), ('e', 'i4'),
('f', 'i4', (256,))])
data = np.fromfile(file, dtype=dt)
df = pd.DataFrame(data)
# Or if you want to explicitly set the column names
df = pd.DataFrame(data, columns=data.dtype.names)
Run Code Online (Sandbox Code Playgroud)
编辑:
data.to_list().谢谢fxxcolumns参数的示例小智 10
最近我遇到了类似的问题,但结构要大得多.我想我发现使用实用方法DataFrame.from_records改进了mowen的答案.在上面的例子中,这将给出:
import numpy as np
import pandas as pd
# Create a dtype with the binary data format and the desired column names
dt = np.dtype([('a', 'i4'), ('b', 'i4'), ('c', 'i4'), ('d', 'f4'), ('e', 'i4'), ('f', 'i4', (256,))])
data = np.fromfile(file, dtype=dt)
df = pd.DataFrame.from_records(data)
Run Code Online (Sandbox Code Playgroud)
就我而言,它显着加快了这个过程.我假设改进来自于不必创建中间Python列表,而是直接从Numpy结构化数组创建DataFrame.
| 归档时间: |
|
| 查看次数: |
18915 次 |
| 最近记录: |