使用python h5py读取.mat文件中的所有变量 [英] Reading ALL variables in a .mat file with python h5py

查看:508
本文介绍了使用python h5py读取.mat文件中的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从'.mat'v7.3文件中提取所有变量,并将它们转换为NumPy数组.有没有一种通用的方法,最好不需要指定变量名?如何从h5py.File获取所有当前的变量名称,然后检查其尺寸?

I'm trying to pull in all the variables from a '.mat' v7.3 file, and turn them into NumPy arrays. Is there a way to do this generically, preferably not needing to specify variable names? How can you get all present variable names from a h5py.File, then check their dimensions?

例如

 import numpy as np, h5py

 file = h5py.File('data.mat','r')
 for "all variables in mat file"
     ...fill numpy array
 end

推荐答案

看到一些评论和

After seeing some of the comments, and the documentations for H5PY Groups, I've found that you can iterate through all of the H5PY "Items" to get the value associated to each variable name. I gave an example below. Please post if their is a better way of grabbing the variable names and values.

注:该示例仅提取包含数字数组(h5py.Dataset)的变量的值.如果您有嵌套的组或单元格数组,则需要进一步访问它们以获取值.

import numpy as np
import h5py

f = h5py.File('simdata_020_01.mat','r')
variables = f.items()

for var in variables:
    name = var[0]
    data = var[1]
    print "Name ", name  # Name
    if type(data) is h5py.Dataset:
        # If DataSet pull the associated Data
        # If not a dataset, you may need to access the element sub-items
        value = data.value
        print "Value", value  # NumPy Array / Value

这篇关于使用python h5py读取.mat文件中的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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