读取Matlab的单元格数组,保存为带有H5py的v7.3 .mat文件

时间:2015-02-01 02:04:17

标签: python matlab h5py

我将一个单元格数组保存为Matlab中的.mat文件,如下所示:

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

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

我试过

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!']列表?

3 个答案:

答案 0 :(得分:8)

用Matlab写作:

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

enter image description here

用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!']]

答案 1 :(得分:6)

这个答案应该被视为对Franck Dernoncourt的答案的补充,这对于所有包含&#39; flat&#39;数据(适用于7.3及以上版本的mat文件)。

我遇到了一个我有嵌套数据的情况(例如命名单元格数组中的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]

这适用于嵌套数据的原因: 如果您查看要在更深层次检索的数据集的类型,则会显示&#39; h5py.h5r.Reference &#39;。为了实际检索引用指向的数据,您需要提供对文件对象的引用

答案 2 :(得分:4)

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

hdf5storage

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

相关问题