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

查看:33
本文介绍了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 读回 python.我尝试了以下方法:

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)

现在可以通过以下方式访问它

Now it was possible to access it by

>> 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天全站免登陆