Python:使用h5py和NumPy从MATLAB .mat文件读取str时出现问题 [英] Python: Issue reading in str from MATLAB .mat file using h5py and NumPy

查看:204
本文介绍了Python:使用h5py和NumPy从MATLAB .mat文件读取str时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难将MATLAB .mat文件中的'str'变量'Et'(Endtime)和'St'(Starttime)加载到Python中.

I am having difficulty loading in 'str' variables 'Et' (Endtime) and 'St' (Starttime) from a MATLAB .mat file into Python.

我想要与MATLAB中相同的输出.相反,我在尝试解决此问题时遇到了问题.有关Python代码和输出,请参见下文.

I want identical output as in MATLAB. Instead I have had issues trying to solve this. See below for Python code and output.

# 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'这是日期和时间.

I want to have a string in python equal to the string in MATLAB. In other words, I want print(data["Et"]) = '01011212000000' which is the date and time.

我该如何解决?

MATLAB中的数据示例:

An example of the data in MATLAB:

推荐答案

如果您不介意存储在file.mat中的etimestime的变量类型,则可以将它们存储为char类型string中的内容,您可以通过bytes(f.get(your_variable).value).decode('utf-8')在Python中阅读它们.就您而言:

If you don't mind the variable type of etime and stime stored in file.mat and you can store them as type char instead of string, you could read them in Python by: bytes(f.get(your_variable).value).decode('utf-8'). In your case:

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

I'm sure there is also a way of reading string type, but this might be the simplest solution.

这篇关于Python:使用h5py和NumPy从MATLAB .mat文件读取str时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆