2

Given two set of dict saved using numpy savez as below

import numpy as np
from numpy import load
names=['t1','t2','t3']
arr_name = np.array(names)
arr_val = np.array([1,2,3])


np.savez('data.npz', dict_one=dict(fone=arr_name,nval=arr_val),
         dict_two=dict(fone=arr_name,nval=arr_val))

When reload the data as

dict_data = load('data.npz',allow_pickle=True)
ndata=dict_data['dict_one']
opt=ndata['fone']

The compiler return an error

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

May I know what is the issue here,and whether this is a good practice of saving multiple dict with numpy arrays in it?

The output for print(ndata)

{'fone': array(['t1', 't2', 't3'], dtype='<U2'), 'nval': array([1, 2, 3])}

The output for print(dict_data )

<numpy.lib.npyio.NpzFile object at 0x7fe8887c6850>

Spec:

numpy 1.21.1 and Python 3.9.
mpx
  • 3,081
  • 2
  • 26
  • 56

1 Answers1

3

The error says you can't index an array with a string like 'fone'.

savez saves arrays, you gave it dicts. It has wrapped each dict in the 1 element object dtype array:

In [296]: names=['t1','t2','t3']
     ...: arr_name = np.array(names)
     ...: arr_val = np.array([1,2,3])
     ...: 
     ...: 
     ...: np.savez('data.npz', dict_one=dict(fone=arr_name,nval=arr_val),
     ...:          dict_two=dict(fone=arr_name,nval=arr_val))

In [298]: dict_data = np.load('data.npz',allow_pickle=True)
     ...: ndata=dict_data['dict_one']
In [299]: ndata
Out[299]: 
array({'fone': array(['t1', 't2', 't3'], dtype='<U2'), 'nval': array([1, 2, 3])},
      dtype=object)

Use item (or indexing) to extract the element from the array

In [300]: ndata.item()
Out[300]: {'fone': array(['t1', 't2', 't3'], dtype='<U2'), 'nval': array([1, 2, 3])}
In [301]: ndata.item()['fone']
Out[301]: array(['t1', 't2', 't3'], dtype='<U2')
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • I think this is a duplicate but wasted my close vote: https://stackoverflow.com/q/17912878/2988730 – Mad Physicist Aug 21 '21 at 15:25
  • @MadPhysicist, yes, I recently wrote a similar answer to another SO. – hpaulj Aug 21 '21 at 15:27
  • An overlapping question, https://stackoverflow.com/questions/68842969/call-array-with-keyword-argument-from-npz-in-numpy. Not quite a duplicate, but part of my answer uses this `item()` trick. – hpaulj Aug 21 '21 at 15:34