python把mat数据里的数组,如何在python中显示.mat文件中的数组元素

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

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()

解决方案

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.

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):

To test if variable node is a Dataset use:

if isinstance(node, h5py.Dataset):

To test if variable node is an Object Dataset use:

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

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

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值