是否可以在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变量,值是分配给这些变量的对象。

其他回答

也可以使用hdf5storage库。关于matlab版本支持的详细信息,这里是官方文档。

import hdf5storage

label_file = "./LabelTrain.mat"
out = hdf5storage.loadmat(label_file) 

print(type(out)) # <class 'dict'>
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文件。

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

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

需要导入,导入scipy.io…

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