是否可以在Python中读取二进制MATLAB .mat文件?

我看到SciPy声称支持读取.mat文件,但我没有成功。我安装了SciPy 0.7.0版本,但找不到loadmat()方法。


当前回答

读取文件

import scipy.io
mat = scipy.io.loadmat(file_name)

检查MAT变量的类型

print(type(mat))
#OUTPUT - <class 'dict'>

字典中的键是MATLAB变量,值是分配给这些变量的对象。

其他回答

from os.path import dirname, join as pjoin
import scipy.io as sio
data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data')
mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat')
mat_contents = sio.loadmat(mat_fname)

你可以使用上面的代码来读取Python中默认保存的.mat文件。

安装了MATLAB 2014b或更新版本后,可以使用MATLAB for Python引擎:

import matlab.engine
eng = matlab.engine.start_matlab()
content = eng.load("example.mat", nargout=1)

在我自己努力解决这个问题并尝试其他库(我不得不说mat4py也是一个很好的库,但有一些限制)之后,我构建了这个库(“matdata2py”),它可以处理大多数变量类型,对我来说最重要的是“字符串”类型。.mat文件需要保存在-V7.3版本中。我希望这对社区有用。

安装:

pip install matdata2py

如何使用这个库:

import matdata2py as mtp

加载Matlab数据文件:

Variables_output = mtp.loadmatfile(file_Name, StructsExportLikeMatlab = True, ExportVar2PyEnv = False)
print(Variables_output.keys()) # with ExportVar2PyEnv = False the variables are as elements of the Variables_output dictionary. 

使用ExportVar2PyEnv = True,你可以分别看到每个变量作为与Mat文件中保存的同名的python变量。

国旗的描述

StructsExportLikeMatlab = True/False结构导出为字典格式(False)或类似于Matlab的基于点的格式(True)

ExportVar2PyEnv = True/False将单个字典中的所有变量导出(True)或作为单独的单独变量导出到python环境中(False)

需要导入,导入scipy.io…

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

将mat文件读入混合数据类型的pandas dataFrame

import scipy.io as sio
mat=sio.loadmat('file.mat')# load mat-file
mdata = mat['myVar']  # variable in mat file 
ndata = {n: mdata[n][0,0] for n in mdata.dtype.names}
Columns = [n for n, v in ndata.items() if v.size == 1]
d=dict((c, ndata[c][0]) for c in Columns)
df=pd.DataFrame.from_dict(d)
display(df)