我已经看到了一些将 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 中也没有),它允许我准确指定要在每个字段中写入的字节。