【问题标题】:Saving and loading Python dict with savemat results in error使用 savemat 保存和加载 Python dict 会导致错误
【发布时间】:2023-03-17 18:10:02
【问题描述】:

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

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'

【问题讨论】:

    标签: python scipy mat-file


    【解决方案1】:

    看起来 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)
    

    【讨论】:

    • 这似乎对我不起作用:b['a'].dtype.names 什么也不返回,b['a']['test1'] 返回Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; ValueError: field named test1 not found.
    【解决方案2】:

    您似乎在假设scipy.io.savemat 旨在能够保存标准字典的情况下进行操作。我不相信是这样的。字典参数保存写出到 Matlab 文件中的 numpy 数组 的名称。所以你可以做这样的事情

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      相关资源
      最近更新 更多