【问题标题】:Saving dictionary of header information using numpy.savez()使用 numpy.savez() 保存标题信息字典
【发布时间】:2014-04-14 11:12:22
【问题描述】:

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

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

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

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

我收到以下错误:

    ValueError: field named TIME not found.

在保存之前,标题类型为“dict”。保存/加载后,输入“numpy.ndarray”。我可以将其转换回字典吗?或者有没有更好的方法来达到同样的效果?

【问题讨论】:

  • timeposition 是什么?如果是数组,为什么不直接保存:np.savez(filename, data=data, TIME=time, POSITION=position)
  • 它们只是数值。我的标题字典有几个参数:采样率、持续时间等。我可以使用您建议的方法,但我希望将它们作为单个字典发送。

标签: python numpy dictionary header


【解决方案1】:

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)

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

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

所以你可以通过这样做来解决:

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

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

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

【讨论】:

    【解决方案2】:

    正如@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
    


    这根本不是你的问题,但下面的小class Bag 很好, 你可以在 IPython 中bag.<tab>
    #...............................................................................
    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)
    

    【讨论】:

    • 我从来不知道 [()] 技巧来索引零维数组。巫术!
    猜你喜欢
    • 2012-04-21
    • 1970-01-01
    • 2013-05-09
    • 2011-09-29
    • 2012-10-11
    • 1970-01-01
    • 2018-02-18
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多