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

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


当前回答

除了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')

其他回答

Scipy可以很好地加载.mat文件。 我们可以使用get()函数将其转换为numpy数组。

mat = scipy.io.loadmat('point05m_matrix.mat')

x = mat.get("matrix")
print(type(x))
print(len(x))

plt.imshow(x, extent=[0,60,0,55], aspect='auto')
plt.show()

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

import hdf5storage

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

print(type(out)) # <class 'dict'>

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

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

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

在python中上传和读取mat文件

用python安装mat4py。在成功安装后,我们得到: 成功安装mat4py-0.5.0。 从mat4py导入loadmat。 保存文件的实际位置在一个变量。 使用python将mat文件格式加载到数据值 PIP安装mat4py 从mat4py导入loadmat boston = r"E:\Downloads\boston.mat" data = loadmat(boston, meta=False)