简体   繁体   English

Python ndarray 与 dtype=object

[英]Python ndarray with dtype=object

How can I access data inside a numpy array with dtype=object?如何使用 dtype=object 访问 numpy 数组中的数据?

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

The following gives IndexError.下面给出 IndexError。

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

Since you passed in the dict to numpy.array() without putting it in a list, this is a zero-dimensional array.由于您将 dict 传递给numpy.array()而不将其放入列表中,因此这是一个零维数组。 To index into a zero-dimensional array, you can use b.item() to access the element inside.要索引到零维数组,您可以使用b.item()来访问里面的元素。 For completeness, to access the data in the "a" key in your dictionary, you can use this.为了完整起见,要访问字典中"a"键中的数据,您可以使用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM