如何在python中的.mat文件中显示数组的元素 [英] how to display elements of arrays in a .mat file in python

查看:196
本文介绍了如何在python中的.mat文件中显示数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次尝试使用" .mat"文件.我将使用" .mat"文件的数据,但是无法打开数组的元素.谁能帮我?由于"* .mat"文件> 7.3,因此无法使用Scipy.io

This is the first time that I try to work with ".mat" files. I am going to use the data of a ".mat" file, but the elements of the arrays can not be opened. Can any one help me? Since the "*.mat" file is > 7.3, I can not use Scipy.io

 import numpy as np
 import h5py

 f = h5py.File('data.mat')
 for i in f.keys():
    aa = f[i]
    aa=np.array(aa)
    print i,':','\n',aa

当我使用aa = np.array(aa)[0]时,输出将是f.key()的名称,但是我需要f.key()的元素

When I use aa=np.array(aa)[0], the output would be the name of the f.key(), but I need the elements of the f.key()

推荐答案

@hpaulj所述,您需要确定哪些对象是组,哪些对象是数据集.对于Matlab数据集,您需要确定哪些是数组,哪些是对象(对象指向文件中的其他HDF5对象).直到您对HDF5和h5py满意为止,最简单的方法是使用HDF集团的 HDFView 实用程序.

As @hpaulj commented, you need to determine which objects are Groups and which are Datasets. And with Matlab datasets, you need to determine which are arrays and which are objects (objects point to other HDF5 objects in your file). Until you're comfortable with HDF5 and h5py, the easiest way to do this is with the HDFView utility from the HDF Group.

准备编写代码时,可以使用isinstance()引用h5py对象来务实地进行编码.
要测试变量node是否为 Group ,请使用:

When you're ready to code, you can do it pragmatically with isinstance() referencing h5py objects.
To test if variable node is a Group use:

if isinstance(node, h5py.Group):

要测试变量node是否为数据集,请使用:

To test if variable node is a Dataset use:

if isinstance(node, h5py.Dataset):

要测试变量node是否为对象数据集,请使用:

To test if variable node is an Object Dataset use:

if (node.dtype == 'object') :

您可以使用visititems(-function-)递归遍历对象树,并对每个对象调用-function-.

You can use visititems(-function-) to loop recursively down an object tree, calling -function- with each object.

这是一个非常简单的示例来演示.将文件名放在foo.hdf5位置并运行.警告:如果您有很多组和数据集,这会产生很多输出.一旦了解了文件模式,就应该能够访问数据集.如果找到对象数据集,请阅读我的链接答案以取消引用它们.

Here's a very simple example to demonstrate. Put your filename in the place of foo.hdf5 and run. Warning: This creates a lot of output if you have a lot of groups and datasets. Once you understand your file schema, you should be able to access the datasets. If you find object datasets, read my linked answer to dereference them.

import numpy as np
import h5py

def visitor_func(name, node):
    if isinstance(node, h5py.Group):
        print(node.name, 'is a Group')
    elif isinstance(node, h5py.Dataset):
       if (node.dtype == 'object') :
            print (node.name, 'is an object Dataset')
       else:
            print(node.name, 'is a Dataset')   
    else:
        print(node.name, 'is an unknown type')         
#########    

print ('testing hdf5 matlab file')
h5f = h5py.File('foo.hdf5')

h5f.visititems(visitor_func)   

h5f.close()

这篇关于如何在python中的.mat文件中显示数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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