I have a numpy array like this
a = np.array(1)
Now if I want to get 1 back from this array, how do I retrieve this?
I have tried
a[0], a(0)
but they give error:
IndexError: 0-d arrays can't be indexed
or
TypeError: 'numpy.ndarray' object is not callable
I even tried to do some weird flattening but I am pretty sure that it shouldn’t be that complicated. I am getting errors in both. All I want is that 1 as an int?
What you create with
is a zero-dimensional array, and these cannot be indexed. You also don’t need to index it — you can use
adirectly as if it were a scalar value. If you really need the value in a different type, sayfloat, you can explicitly convert it withfloat(a). If you need it in the base type of the array, you can usea.item()ora[()].Note that the zero-dimensional array is mutable. If you change the value of the single entry in the array, this will be visible via all references to the array you stored. Use
a.item()if you want to store an immutable value.If you want a one-dimensional array with a single element instead, use
You can access the single element with
a[0]now.