scipy.io.loadmat嵌套结构(即字典) [英] scipy.io.loadmat nested structures (i.e. dictionaries)

查看:341
本文介绍了scipy.io.loadmat嵌套结构(即字典)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用给定的例程(如何用scipy加载Matlab .mat文件),我无法访问更深入的嵌套结构以将其恢复到字典中

Using the given routines (how to load Matlab .mat files with scipy), I could not access deeper nested structures to recover them into dictionaries

提出问题我进一步详细地介绍了以下玩具示例:

To present the problem I run into in more detail, I give the following toy example:

load scipy.io as spio
a = {'b':{'c':{'d': 3}}}
# my dictionary: a['b']['c']['d'] = 3
spio.savemat('xy.mat',a)

现在我要读取mat-File蟒蛇。我尝试了以下内容:

Now I want to read the mat-File back into python. I tried the following:

vig=spio.loadmat('xy.mat',squeeze_me=True)

如果我现在想访问我得到的字段:

If I now want to access the fields I get:

>> vig['b']
array(((array(3),),), dtype=[('c', '|O8')])
>> vig['b']['c']
array(array((3,), dtype=[('d', '|O8')]), dtype=object)
>> vig['b']['c']['d']
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/<ipython console> in <module>()

ValueError: field named d not found.

但是,通过使用选项 struct_as_record = False 该字段可以访问:

However, by using the option struct_as_record=False the field could be accessed:

v=spio.loadmat('xy.mat',squeeze_me=True,struct_as_record=False)

现在可以通过

>> v['b'].c.d
array(3)


推荐答案

这里是重建字典的函数,只是使用这个loadmat而不是scipy.io的loadmat:

Here are the functions, which reconstructs the dictionaries just use this loadmat instead of scipy.io's loadmat:

import scipy.io as spio

def loadmat(filename):
    '''
    this function should be called instead of direct spio.loadmat
    as it cures the problem of not properly recovering python dictionaries
    from mat files. It calls the function check keys to cure all entries
    which are still mat-objects
    '''
    data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)
    return _check_keys(data)

def _check_keys(dict):
    '''
    checks if entries in dictionary are mat-objects. If yes
    todict is called to change them to nested dictionaries
    '''
    for key in dict:
        if isinstance(dict[key], spio.matlab.mio5_params.mat_struct):
            dict[key] = _todict(dict[key])
    return dict        

def _todict(matobj):
    '''
    A recursive function which constructs from matobjects nested dictionaries
    '''
    dict = {}
    for strg in matobj._fieldnames:
        elem = matobj.__dict__[strg]
        if isinstance(elem, spio.matlab.mio5_params.mat_struct):
            dict[strg] = _todict(elem)
        else:
            dict[strg] = elem
    return dict

这篇关于scipy.io.loadmat嵌套结构(即字典)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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