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

问题描述 投票:0回答:3

我很难将'str'变量'Et'(Endtime)和'St'(Starttime)从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中的数据示例:example

python string matlab numpy h5py
3个回答
1
投票

如果你不介意存储在etime中的变量类型的stimefile.mat,你可以将它们存储为类型char而不是string,你可以用Python阅读它们:bytes(f.get(your_variable).value).decode('utf-8')。在你的情况下:

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类型,但这可能是最简单的解决方案。


1
投票

当我需要加载.mat我使用scipy,它工作正常。试试这个:

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

我认为它会起作用。祝好运。


1
投票

在Octave

>> 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

Opening a mat file using h5py and convert data into a numpy matrix

====

bytes也适用于我的档案

In [220]: bytes(f['xt/value'].value)
Out[220]: b'a string'
In [221]: bytes(f['et/value'].value)
Out[221]: b'0101121200000'
© www.soinside.com 2019 - 2024. All rights reserved.