我看到了一些将Python中格式化的二进制文件读给Pandas的方法, 也就是说,我使用的代码是使用NumPy fromfile读取的,该文件的格式是使用dtype给定的结构。
import numpy as np
import pandas as pd
input_file_name = 'test.hst'
input_file = open(input_file_name, 'rb')
header = input_file.read(96)
dt_header = np.dtype([('version', 'i4'),
('copyright', 'S64'),
('symbol', 'S12'),
('period', 'i4'),
('digits', 'i4'),
('timesign', 'i4'),
('last_sync', 'i4')])
header = np.fromstring(header, dt_header)
dt_records = np.dtype([('ctm', 'i4'),
('open', 'f8'),
('low', 'f8'),
('high', 'f8'),
('close', 'f8'),
('volume', 'f8')])
records = np.fromfile(input_file, dt_records)
input_file.close()
df_records = pd.DataFrame(records)
# Now, do some changes in the individual values of df_records
# and then write it back to a binary file
现在,我的问题是如何把这个写回一个新文件。我在NumPy中找不到任何函数(在Pandas中也找不到)允许我精确指定要在每个字段中写入的字节数。
熊猫现在提供的a wide variety of formats比tofile()更稳定。to file()最适合于快速文件存储,在这种情况下,您不希望文件在另一台计算机上使用,因为数据可能具有不同的endianness(big-/little endian)。
我目前正在使用HDF5,但如果我在亚马逊,我会使用拼花。
使用to_hdf的示例:
但是,HDF5格式可能不适合长期存档,因为它是fairly complex。它有150页的规范,只有一个300000行的C实现。
我不清楚} method of the ^{} 。
DataFrame
是视图还是副本,但假设它是副本,您可以使用^{这将返回一个记录数组,然后可以使用
tofile
将其放入磁盘。例如
数据将以压缩字节的形式驻留在内存中,其格式由重新排列数据类型描述。
相关问题 更多 >
编程相关推荐