如何使用h5py编写.mat-v7.3文件?

问题描述 投票:0回答:1

在阅读了 Create .mat v7.3 files from Python using hdf5storage 的答案后,我已经能够使用 hdf5storage 编写 .mat-v7.3 文件,但我相信通过设置可以达到相同的结果编写我的 .mat 文件时使用正确的标题。

假设我有一个由以下数据构建的 Pandas 数据框:

[
 {'time': 0, 'sig0': 0.6153857, 'sig1': 0.070254125, 'sig2': 0.025843188}, 
 {'time': 586576558, 'sig0': 0.6015989, 'sig1': 0.7131938, 'sig2': 0.42542282},
...
 {'time': 589999558, 'sig0': 0.1598977, 'sig1': 0.6131938, 'sig2': 0.88882282}
]

如何解析此数据并创建兼容 .mat-v7.3 的 hdf5 文件?

python h5py mat-file hdf5storage
1个回答
0
投票

如果您访问 h5storage 的 GitHub 存储库,您将找到此处定义的标头。它基本上表示您需要一个 512 字节的元数据块,其中包含日期时间创建、平台版本、字符编码等内容。

然后,您所需要做的就是根据数据框列创建数据集。这是结合这两个步骤的示例:

import datetime
import h5py
import pandas as pd
import sys

data = [
    {'time': 0, 'sig0': 0.6153857, 'sig1': 0.070254125, 'sig2': 0.025843188},
    {'time': 586576558, 'sig0': 0.6015989, 'sig1': 0.7131938, 'sig2': 0.42542282},
    {'time': 589999558, 'sig0': 0.1598977, 'sig1': 0.6131938, 'sig2': 0.88882282}
]
df = pd.DataFrame(data)

def mat_export(df, export_path):
    def write_userblock(filename):
        now = datetime.datetime.now()
        v = sys.version_info
        platform_version = f"CPython {v.major}.{v.minor}.{v.micro}"
        created_on = now.strftime("%a %b %d %H:%M:%S %Y")
        header = f"MATLAB 7.3 MAT-file, Platform: {platform_version}, Created on: {created_on} HDF5 schema 1.00 ."
        header_bytes = bytearray(header, "utf-8")
        header_bytes.extend(bytearray((128 - 12 - len(header_bytes)) * " ", "utf-8"))
        header_bytes.extend(bytearray.fromhex("00000000 00000000 0002494D"))
        with open(filename, "r+b") as f:
            f.write(header_bytes)

    def write_h5py(data, filename, userblock_size=512):
        with h5py.File(filename, "w", userblock_size=userblock_size) as f:
            pass  # Close to write the userblock
        write_userblock(filename)
        with h5py.File(filename, "a") as f:
            for column in data.columns:
                f.create_dataset(column, data=data[column], maxshape=(None,), chunks=True)

    write_h5py(df, export_path)

export_path = 'your_data.mat'
mat_export(df, export_path)

就是这样,我希望这个问答可以帮助人们尝试使用 Python 导出 .mat 兼容的 hdf5 文件。

© www.soinside.com 2019 - 2024. All rights reserved.