python - 从 Pandas Dataframe 写入格式化的二进制文件

标签 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 中)允许我准确指定要在每个要写入的字段中使用的字节。

最佳答案

Pandas 现在提供 a wide variety of formats比 tofile() 更稳定。 tofile() 最适用于快速文件存储,您不希望文件在数据可能具有不同字节顺序(大端/小端)的不同机器上使用。

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

对于中小型文件,我更喜欢 CSV,因为格式正确的 CSV 可以存储任意字符串数据,人类可读,并且在实现前两个目标的同时与任何格式一样简单。

我曾经使用过 HDF5,但如果我在亚马逊上,我会考虑使用 parquet。

使用示例 to_hdf :

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

我不再喜欢 HDF5 格式。由于它是fairly complex,因此它对长期归档具有严重的风险。 .它有 150 页的规范,只有一个 300,000 行 C 实现。

相比之下,只要您专门使用 Python 工作,pickle format claims long term stability :

The pickle serialization format is guaranteed to be backwards compatible across Python releases provided a compatible pickle protocol is chosen and pickling and unpickling code deals with Python 2 to Python 3 type differences if your data is crossing that unique breaking change language boundary.

但是,pickles 允许任意代码执行,因此应谨慎处理来历不明的 pickle。

关于python - 从 Pandas Dataframe 写入格式化的二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26348095/

相关文章:

行的 python pandas 着色

python - 在 pandas 中创建质量分数列

python - 值错误 : I/O operation on closed file

python - Jupyter Notebook : Import . ipynb 文件并在其他 .ipynb 文件中访问它的方法给出错误

python - 如何让 Boto 返回 EC2 实例 - S3 工作正常

python - 计算 torch 张量数组的平均值和标准差

python - pandas.series.copy 不创建新对象

python - 为什么 Python 3 http.client 比 python-requests 快这么多?

python - 滚动平均 pandas DataFrame 的所有值

python - 通过 scipy.io.loadmat 将 matlab 3D 矩阵传输到 python 3D 数组会出错