Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving dictionary of header information using 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']

I get the following error:

    ValueError: field named TIME not found.

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?

like image 414
user3403779 Avatar asked Mar 11 '14 03:03

user3403779


1 Answers

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)

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'][()]

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

>>> h
{'POSITION': (23, 54), 'TIME': 23.5}
like image 52
askewchan Avatar answered Oct 29 '22 01:10

askewchan