Dictionary in a numpy array?

2019-02-22 01:42发布

How do I access the dictionary inside the array?

import numpy as np
x = np.array({'x': 2, 'y': 5})

My initial thought:

x['y']

Index Error: not a valid index

x[0]

Index Error: too many indices for array

2条回答
Bombasti
2楼-- · 2019-02-22 01:59

If you add square brackets to the array assignment you will have a 1-dimensional array:

x = np.array([{'x': 2, 'y': 5}])

then you could use:

x[0]['y']

I believe it would make more sense.

查看更多
等我变得足够好
3楼-- · 2019-02-22 02:01

You have a 0-dimensional array of object dtype. Making this array at all is probably a mistake, but if you want to use it anyway, you can extract the dictionary by indexing the array with a tuple of no indices:

x[()]

or by calling the array's item method:

x.item()
查看更多
登录 后发表回答