从Pandas Dataframe编写格式化的二进制文件

时间:2014-10-13 20:10:05

标签: python numpy pandas binaryfiles

我已经看到一些方法可以将Python中的格式化二进制文件读取到Pandas中, 也就是说,我正在使用这个代码,该代码使用NumPy从使用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中都没有),它允许我准确指定要在每个字段中使用的字节。

2 个答案:

答案 0 :(得分:2)

我不清楚DataFrame是视图还是副本,但假设它是副本,您可以使用to_records method of the DataFrame

这会返回一个记录数组,然后您可以使用tofile将其放入磁盘。

e.g。

df_records = pd.DataFrame(records)
# do some stuff
new_recarray = df_records.to_records()
new_recarray.tofile("myfile.npy")

数据将作为压缩字节驻留在内存中,格式为recarray dtype。

答案 1 :(得分:1)

Pandas现在提供的a wide variety of formats比tofile()更稳定。 tofile()最适合用于快速文件存储,在这种情况下,您不希望文件在数据可能具有不同字节序(big- / little-endian)的其他计算机上使用。

Format Type Data Description     Reader         Writer
text        CSV                  read_csv       to_csv
text        JSON                 read_json      to_json
text        HTML                 read_html      to_html
text        Local clipboard      read_clipboard to_clipboard
binary      MS Excel             read_excel     to_excel
binary      HDF5 Format          read_hdf       to_hdf
binary      Feather Format       read_feather   to_feather
binary      Parquet Format       read_parquet   to_parquet
binary      Msgpack              read_msgpack   to_msgpack
binary      Stata                read_stata     to_stata
binary      SAS                  read_sas    
binary      Python Pickle Format read_pickle    to_pickle
SQL         SQL                  read_sql       to_sql
SQL         Google Big Query     read_gbq       to_gbq

我目前正在使用HDF5,但是如果我在Amazon上,我会使用镶木地板。

使用to_hdf的示例:

df.to_hdf('tmp.hdf','df', mode='w')
df2 = pd.read_hdf('tmp.hdf','df')

但是,HDF5格式fairly complex可能不是长期存档的最佳选择。它具有150页的规范,并且只有一个300,000行C实现。