簡體   English   中英

使用H5py讀取保存為v7.3 .mat文件的Matlab單元格數組

[英]Reading a Matlab's cell array saved as a v7.3 .mat file with H5py

我將單元格數組保存為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!']

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

此答案應視為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]

之所以適用於嵌套數據,是因為:如果您在更深的層次上查看要檢索的數據集的類型,它將顯示為“ h5py.h5r.Reference ”。 為了實際檢索引用所指向的數據,您需要將該引用提供給文件對象

我知道這是一個老問題。 但是我找到了一個解決這個問題的方法:

hdf5存儲

它可以通過pip進行安裝,並且在python 3.6和7.3之前和之后的matlab文件中均可正常使用。 對於較舊的文件,它scipy.io.loadmat根據文檔調用scipy.io.loadmat

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM