我正在尝试保存一个数据数组以及标题信息。目前,我使用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‘类型。我能把它转换回字典吗?还是有更好的方法来达到同样的结果?
发布于 2014-03-11 03:16:00
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}
发布于 2014-06-18 14:44:32
正如@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)
https://stackoverflow.com/questions/22315595
复制相似问题