Home > Back-end >  Python ndarray with dtype=object
Python ndarray with dtype=object

Time:12-19

How can I access data inside a numpy array with dtype=object ?

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

The following gives IndexError.

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

CodePudding user response:

Since you passed in the dict to numpy.array() without putting it in a list, this is a zero-dimensional array. To index into a zero-dimensional array, you can use b.item() to access the element inside. For completeness, to access the data in the "a" key in your dictionary, you can use this.

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