0

I encounter the following errors when converting an integer to a numpy array:

a = 150
b = np.array(a)
b[0]
*** IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed

I expect the output of b[0] is 150, but get the IndexError. Why?

4
  • 1
    the shape of your array is (). you can use np.array([a]) if you want to define a one dimentional array. Commented Aug 18, 2022 at 10:37
  • Yes. And I don't understand the output of b is array(150) instead of array([150]). What does it mean? Commented Aug 18, 2022 at 10:41
  • 1
    notice that the output is based on the input shape. when you pass an scalar like 150, it's reasonable for output that have a dimensional of 0. by the way you can use indexing like b[()]. Commented Aug 18, 2022 at 12:34
  • 1
    b[()] indexes the 0d array with a 0 element tuple. np.array([150])[0] indexes with a 1d array with 1 index. b.item() is another way of getting the element (from either). Commented Aug 18, 2022 at 15:26

1 Answer 1

2

You have in effect created a scalar or zero dimensional array.

If you need to index into this, try

b = np.array([a])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.