Python:使用 h5py 和 NumPy 从 MATLAB .mat 文件读取 str 问题

Python: Issue reading in str from MATLAB .mat file using h5py and NumPy

我在将 'str' 变量 'Et'(结束时间)和 'St'(开始时间)从 MATLAB .mat 文件加载到 Python 时遇到困难。

我想要与 MATLAB 中相同的输出。相反,我在尝试解决这个问题时遇到了问题。请参阅下面的 Python 代码和输出。

# Import numpy and h5py to load in .mat files
import numpy as np
import h5py 

# Load in Matlab ('-v7.3') data
fname = 'directory/file.mat'
f = h5py.File(fname,'r') 

# create dictionary for data
data= {"average":np.array(f.get('average')),"median":np.array(f.get('median')), \
             "stdev":np.array(f.get('stdev')),"P10":np.array(f.get('p10')), \
             "P90":np.array(f.get('p90')),"St":np.str(f.get('stime')), \
             "Et":np.str(f.get('etime'))}
# All other variables are arrays

print(data["Et"])

输出:

<HDF5 dataset "etime": shape (1, 6), type "<u4">

我希望 python 中的字符串等于 MATLAB 中的字符串。 换句话说,我想要 print(data["Et"]) = '01011212000000' 这是日期和时间。

我该如何解决这个问题?

MATLAB中的数据示例:

当我需要加载 .mat 时,我使用 scipy 并且它工作正常:

import scipy.io
mat = scipy.io.loadmat('fileName.mat')

八度

>> x = 1:10;
>> y = reshape(1:12, 3,4);
>> et = '0101121200000';
>> xt = 'a string';
>> save -hdf5 testh5.mat x y et xt

在 numpy 会话中:

In [130]: f = h5py.File('testh5.mat','r')
In [131]: list(f.keys())
Out[131]: ['et', 'x', 'xt', 'y']
In [132]: list(f['y'].keys())
Out[132]: ['type', 'value']
In [133]: f['x/type'].value
Out[133]: b'range'
In [134]: f['y/type'].value
Out[134]: b'matrix'
In [135]: f['y/value'].value
Out[135]: 
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.],
       [10., 11., 12.]])
In [136]: f['et/type'].value
Out[136]: b'sq_string'
In [137]: f['et/value'].value
Out[137]: 
array([[48],
       [49],
       [48],
       [49],
       [49],
       [50],
       [49],
       [50],
       [48],
       [48],
       [48],
       [48],
       [48]], dtype=int8)
In [138]: f['et/value'].value.ravel().view('S13')
Out[138]: array([b'0101121200000'], dtype='|S13')
In [139]: f['xt/value'].value.ravel().view('S8')
Out[139]: array([b'a string'], dtype='|S8')
In [140]: f.close()

how to import .mat-v7.3 file using h5py

====

bytes 也适用于我的文件

In [220]: bytes(f['xt/value'].value)
Out[220]: b'a string'
In [221]: bytes(f['et/value'].value)
Out[221]: b'0101121200000'

如果您不介意 etimestime 的变量类型存储在 file.mat 中,您可以将它们存储为类型 char 而不是 [=15] =],您可以通过 bytes(f.get(your_variable).value).decode('utf-8') 在 Python 中阅读它们。在你的情况下:

data = {
    "average": np.array(f.get('average')),
    "median": np.array(f.get('median')),
    "stdev": np.array(f.get('stdev')),
    "P10": np.array(f.get('p10')),
    "P90": np.array(f.get('p90')),
    "St": bytes(f.get('stime')[:]).decode('utf-8'),
    "Et": bytes(f.get('etime')[:]).decode('utf-8')
}

我确定还有一种读取 string 类型的方法,但这可能是最简单的解决方案。