Saving a dictionary of header information using numpy.savez ()

I am trying to save an array of data along with header information. I am currently using numpy.savez () to store header (dictionary) information in one array and 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 download and read a file, I cannot index the dictionary of headers.

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

I get the following error:

    ValueError: field named TIME not found.

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

+4
source share
2 answers

np.savez . dict, 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 storing a dict, not numbers.

:

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

0d:

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

@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 , 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)
+1

Source: https://habr.com/ru/post/1531086/


All Articles