How can I access data inside a numpy array with dtype=object
?
JavaScript
x
2
1
b = numpy.array({"a":[1,2,3]}, dtype=object)
2
The following raises an IndexError
.
JavaScript
1
2
1
print(b["a"])
2
JavaScript
1
2
1
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
2
Advertisement
Answer
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.
JavaScript
1
3
1
>>> b.item()["a"]
2
[1, 2, 3]
3