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

Fra*_*urt 7 python matlab h5py

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

test = {'hello'; 'world!'};
save('data.mat', 'test', '-v7.3')
Run Code Online (Sandbox Code Playgroud)

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

我试过了

f = h5py.File('data.mat', 'r')
print f.get('test')
print f.get('test')[0]
Run Code Online (Sandbox Code Playgroud)

打印出:

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

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

Fra*_*urt 9

用Matlab写作:

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

在此输入图像描述

在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)
Run Code Online (Sandbox Code Playgroud)

输出:

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

[[u'Hello' u'world!']
 [u'Good' u'morning']
 [u'See' u'you!']]
Run Code Online (Sandbox Code Playgroud)


Ben*_*egl 6

这个答案应该被看作是对Franck Dernoncourt的回答的补充,它完全满足所有包含"扁平"数据的单元格数组(对于版本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]
Run Code Online (Sandbox Code Playgroud)

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