Home > Back-end >  python numpy dict to nparry and IndexError: only integers, slices
python numpy dict to nparry and IndexError: only integers, slices

Time:11-12

I made np.array as below

test = np.array({'a': 1})

and I just want get value of test by key 'a' as below

test['a']

and I faced error as below

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

how can i get value of key 'a' in np.array

CodePudding user response:

You have to first take the dict out of the array:

In [142]: test = np.array({'a': 1})
In [143]: test
Out[143]: array({'a': 1}, dtype=object)
In [144]: test.item()
Out[144]: {'a': 1}
In [145]: test.item()['a']
Out[145]: 1

But why did you make this? Why not just a dict? Or a list of dict. numpy doesn't do much for you here.

  • Related