【问题标题】:Reading a Matlab's cell array saved as a v7.3 .mat file with H5py使用 H5py 读取保存为 v7.3 .mat 文件的 Matlab 元胞数组
【发布时间】:2015-02-01 02:04:17
【问题描述】:

我在 Matlab 中将元胞数组保存为 .mat 文件,如下所示:

test = {'hello'; 'world!'};
save('data.mat', 'test', '-v7.3')

如何使用 H5py 将其作为 Python 中的字符串列表导入?

我试过了

f = h5py.File('data.mat', 'r')
print f.get('test')
print f.get('test')[0]

打印出来:

<HDF5 dataset "test": shape (1, 2), type "|O8">
[<HDF5 object reference> <HDF5 object reference>]

如何取消引用它以在 Python 中获取字符串列表 ['hello', 'world!']

【问题讨论】:

    标签: python matlab h5py


    【解决方案1】:

    用 Matlab 编写:

    test = {'Hello', 'world!'; 'Good', 'morning'; 'See', 'you!'};
    save('data.mat', 'test', '-v7.3') % v7.3 so that it is readable by h5py
    

    在 Python 中读取(适用于任何数字或行或列,但假定每个单元格都是一个字符串):

    import h5py
    import numpy as np
    
    data = []
    with h5py.File("data.mat") as f:
        for column in f['test']:
            row_data = []
            for row_number in range(len(column)):            
                row_data.append(''.join(map(unichr, f[column[row_number]][:])))   
            data.append(row_data)
    
    print data
    print np.transpose(data)
    

    输出:

    [[u'Hello', u'Good', u'See'], [u'world!', u'morning', u'you!']]
    
    [[u'Hello' u'world!']
     [u'Good' u'morning']
     [u'See' u'you!']]
    

    【讨论】:

    • ugly...pandas\python\scipy 中是否有更好的解决方案?
    • Scipy 不涉及 v7.3。不知道熊猫。
    【解决方案2】:

    此答案应被视为 Franck Dernoncourt 答案的补充,这对于包含“平面”数据的所有单元格数组(对于 7.3 版及可能更高版本的 mat 文件)完全足够。 p>

    我遇到了一种情况,我有嵌套数据(例如,命名元胞数组中的 1 行元胞数组)。通过执行以下操作,我设法获得了数据:

    # assumption:
    # idx_of_interest specifies the index of the cell array we are interested in
    # (at the second level)
    
    with h5py.File(file_name) as f:
        data_of_interest_reference = f['cell_array_name'][idx_of_interest, 0]
        data_of_interest = f[data_of_interest_reference]
    

    这适用于嵌套数据的原因: 如果您更深入地查看要检索的数据集的类型,它会显示“h5py.h5r.Reference”。为了实际检索引用指向的数据,您需要提供对文件对象的引用

    【讨论】:

      【解决方案3】:

      我知道这是一个老问题。但是我找到了一个可以解决这个问题的包:

      hdf5storage

      它可以通过 pip 安装,并且可以在 python 3.6 上很好地用于 7.3 前后的 matlab 文件。根据文档,对于较旧的文件,它调用scipy.io.loadmat

      【讨论】:

      • 你能分享一下你用来加载字符串数组的代码吗?
      猜你喜欢
      • 2013-10-19
      • 2021-02-23
      • 2018-02-13
      • 2015-01-30
      • 2015-02-24
      • 1970-01-01
      • 2014-01-29
      • 2020-03-10
      • 2013-10-03
      相关资源
      最近更新 更多