使用savemat保存和加载Python dict会导致错误

时间:2012-02-10 18:21:07

标签: python scipy mat-file

这是我得到的错误的最小例子。如果我正确地理解了文档,这应该可行,但似乎我没有。

a={}
a['test1']=1
a['test2']=2
a['test3']=3
import scipy.io as io
io.savemat('temp',{'a':a})
b = io.loadmat('temp')
b['a'].keys()

Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'keys'

2 个答案:

答案 0 :(得分:10)

您似乎在scipy.io.savemat旨在保存标准字典的假设下运行。我不相信是这样的。字典参数包含 numpy arrays 的名称,这些名称写在Matlab文件中。所以你可以做这样的事情

import scipy.io as io
import numpy as np

y1=np.array([1,2,3,4])
y2=np.array([10,20,30,40])
y3=np.array([100,200,300,400])

a={}
a['test1']=y1
a['test2']=y2
a['test3']=y3
io.savemat('temp',a)
b = io.loadmat('temp')

print b['test1']
print b['test2']
print b['test3']

给出:

[[1]
 [2]
 [3]
 [4]]
[[10]
 [20]
 [30]
 [40]]
[[100]
 [200]
 [300]
 [400]]

答案 1 :(得分:2)

看起来像loadmat返回recarray而不是dict。 我用scipy 0.9.0检查了一下。 b['a'].keys()的等效值为b['a'].dtype.names

示例:

In [12]: b['a'].shape
Out[13]: (1, 1)

In [14]: b['a'].dtype.names
Out[16]: ('test1', 'test3', 'test2')

In [17]: b['a']['test1']
Out[17]: array([[[[1]]]], dtype=object)