使用numpy.savez()保存标头信息的字典 [英] Saving dictionary of header information using numpy.savez()

查看:305
本文介绍了使用numpy.savez()保存标头信息的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试保存数据数组以及标头信息.目前,我正在使用numpy.savez()将标头信息(一个字典)保存在一个数组中,并将数据保存在另一个数组中.

I am trying to save an array of data along with header information. Currently, I am using numpy.savez() to save the header information (a dictionary) in one array, and the data in another.

    data = [[1,2,3],[4,5,6]]
    header = {'TIME': time, 'POSITION': position}
    np.savez(filename, header=header, data=data)

但是,当我尝试加载和读取文件时,无法索引标头字典.

When I try to load and read the file, however, I can't index the header dictionary.

    arrays = np.load(filename)
    header = arrays('header')
    data = arrays('data')
    print header['TIME']

我收到以下错误:

    ValueError: field named TIME not found.

在保存之前,标题为"dict"类型.保存/加载后,其类型为"numpy.ndarray".我可以将其转换回字典吗?还是有更好的方法来达到相同的结果?

Before saving, the header is type 'dict'. After saving/loading, it is type 'numpy.ndarray'. Can I convert it back to a dictionary? Or is there a better way to achieve the same result?

推荐答案

np.savez仅保存numpy数组.如果给它一个字典,它将在保存前调用np.array(yourdict).因此,这就是为什么您将type(arrays['header'])视为np.ndarray的原因:

np.savez saves only numpy arrays. If you give it a dict, it will call np.array(yourdict) before saving it. So this is why you see something like type(arrays['header']) as np.ndarray:

arrays = np.load(filename)
h = arrays['header'] # square brackets!!

>>> h
array({'POSITION': (23, 54), 'TIME': 23.5}, dtype=object)

尽管如此,您会注意到它是一个0维的单项数组,其中包含一个字典:

You'll notice if you look at it though, that it is a 0-dimensional, single-item array, with one dict inside:

>>> h.shape
()
>>> h.dtype
dtype('O') # the 'object' dtype, since it's storing a dict, not numbers.

因此您可以通过以下方法解决此问题:

so you could work around by doing this:

h = arrays['header'][()]

神秘的索引从0d数组中获取一个值:

The mysterious indexing gets the one value out of a 0d array:

>>> h
{'POSITION': (23, 54), 'TIME': 23.5}

这篇关于使用numpy.savez()保存标头信息的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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