0

I am trying the following commands in Numpy. An error is reported on assigning new sequence to the array slice. The error is expected, however I could not figure out why dimension is reported in error. Why is dimension 3 reported in error, the array is of 1-dimension

b = np.array([1, 2, 3, 4, 5])
print(b.ndim) # returns 1
b[2:] = [3, 4, 5, 6, 7]

>> ValueError: cannot copy sequence with size 5 to array axis with dimension 3
2
  • The dimension of a numpy array is given by np.shape(array) Commented Feb 26, 2020 at 2:17
  • The receiving slot, b[2:] has space for 3 elements. You could assign a list of size 3, or a scalar, or an array of the right size. Commented Feb 26, 2020 at 3:37

1 Answer 1

2

You are trying to broadcast an array of size 5 to an array of size 3 and numpy is trying to help with broadcasting rules. See the documentation on broadcasting. If you assign with the correct number of values numpy doesn't attempt to do any fancy broadcasting.

b[2:] = [3, 4, 5]

Sign up to request clarification or add additional context in comments.

2 Comments

I have just started with Numpy tutorial, haven't reached broadcasting yet. Thanks for the pointer !
welcome to the wonderful world of Numpy. Keep at it, numpy skills are like super powers

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.