使用numpy.savez()保存标题信息字典

use*_*779 5 python dictionary numpy header

我试图保存一个数据数组和标题信息.目前,我使用numpy.savez()将头信息(字典)保存在一个数组中,将数据保存在另一个数组中.

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

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

    arrays = np.load(filename)
    header = arrays('header')
    data = arrays('data')
    print header['TIME']
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

    ValueError: field named TIME not found.
Run Code Online (Sandbox Code Playgroud)

保存之前,标题是'dict'类型.保存/加载后,它是'numpy.ndarray'类型.我可以将它转换回字典吗?或者有更好的方法来实现相同的结果吗?

ask*_*han 14

np.savez只保存numpy数组.如果你给它一个字典,它会np.array(yourdict)在保存之前调用它.所以这就是为什么你看到这样type(arrays['header'])np.ndarray:

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

>>> h
array({'POSITION': (23, 54), 'TIME': 23.5}, dtype=object)
Run Code Online (Sandbox Code Playgroud)

你会注意到,如果你看它,它是一个0维的单项数组,里面有一个字典:

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

所以你可以这样做:

h = arrays['header'][()]
Run Code Online (Sandbox Code Playgroud)

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

>>> h
{'POSITION': (23, 54), 'TIME': 23.5}
Run Code Online (Sandbox Code Playgroud)


den*_*nis 5

正如 @askewchan 的评论中那样,为什么不呢np.savez( "tmp.npz", data=data, **d )

import numpy as np

data = np.arange( 3 )
time = 23.5
position = [[23, 54], None]
d = dict( TIME=time, POSITION=position )

np.savez( "tmp.npz", data=data, **d )

d = np.load( "tmp.npz" )
for key, val in sorted( d.items() ):
    print key, type(val), val  # note d.TIME is a 0-d array
Run Code Online (Sandbox Code Playgroud)


这根本不是你的问题,但以下几点class Bag很好,你可以bag.<tab>在 IPython 中:

#...............................................................................
class Bag( dict ):
    """ a dict with d.key short for d["key"]
        d = Bag( k=v ... / **dict / dict.items() / [(k,v) ...] )  just like dict
    """
        # aka Dotdict

    def __init__(self, *args, **kwargs):
        dict.__init__( self, *args, **kwargs )
        self.__dict__ = self

    def __getnewargs__(self):  # for cPickle.dump( d, file, protocol=-1)
        return tuple(self)


d = Bag( np.load( "tmp.npz" ))
if d.TIME > 0:
    print "time %g  position %s" % (d.TIME, d.POSITION)
Run Code Online (Sandbox Code Playgroud)