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

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


当前回答

需要导入,导入scipy.io…

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

其他回答

需要导入,导入scipy.io…

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

既不scipy.io。savemat,或scipy.io.loadmat适用于MATLAB数组版本7.3。但好的部分是MATLAB版本7.3文件是hdf5数据集。因此,可以使用包括NumPy在内的许多工具读取它们。

对于Python,您将需要h5py扩展,这需要在您的系统上安装HDF5。

import numpy as np
import h5py
f = h5py.File('somefile.mat','r')
data = f.get('data/variable1')
data = np.array(data) # For converting to a NumPy array

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

在我自己努力解决这个问题并尝试其他库(我不得不说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)

除了v4 (Level 1.0), v6, v7到7.2 matfiles和h5py. io.loadmat之外。文件7.3格式matfiles,有另一种类型的matfiles在文本数据格式而不是二进制,通常由Octave创建,这甚至不能在MATLAB中读取。

scipy.io.loadmat和h5py。文件不能加载它们(在scipy 1.5.3和h5py 3.1.0上测试),我找到的唯一解决方案是numpy.loadtxt。

import numpy as np
mat = np.loadtxt('xxx.mat')