使用savemat保存和加载Python字典会导致错误 [英] Saving and loading Python dict with savemat results in error

查看:468
本文介绍了使用savemat保存和加载Python字典会导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is an minimal example of the error I get. If I understood the documentation correctly, this should be working, but it seems I did not.

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'

推荐答案

您似乎在假设scipy.io.savemat旨在能够保存标准字典的情况下进行操作.我认为情况并非如此.字典参数包含 numpy数组的名称,这些名称被写出到Matlab文件中.所以你可以做这样的事情

You seem to be operating under the assumption that scipy.io.savemat is intended to be able to save a standard dictionary. I don't believe that is the case. The dictionary argument holds the names of numpy arrays which are written out into the Matlab file. So you can do something like this

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]]

这篇关于使用savemat保存和加载Python字典会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆