如何使用 dtype=object 从 ndarray 访问项目

How to access items from ndarray with dtype=object

如何使用 dtype=object 访问 numpy 数组中的数据?

b = numpy.array({"a":[1,2,3]}, dtype=object)

下面提出一个 IndexError.

print(b["a"]) 
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

因为你把字典传给了numpy.array(),没有把它放在一个列表中,所以这是一个零维数组。要对零维数组进行索引,可以使用 b.item() 来访问其中的元素。为了完整起见,要访问字典中 "a" 键中的数据,您可以使用它。

>>> b.item()["a"]
[1, 2, 3]