0

I have a 3-D NumPy array with shape (100, 50, 20). I was trying to slice the third dimension of the array by using the index, e.g., from 1 to 6 and from 8 to 10.

I tried the following code, but it kept reporting a syntax error.

newarr [:,:,1:10] = oldarr[:,:,[1:7,8:11]]

1
  • [1:7,8:11] is an invalid use of slices. The error was caught by the interpreter, but it also has no meaning to numpy. That's a discontinuous set of locations, which has to be enumerated as shown in the answer. Commented Oct 2, 2021 at 23:01

1 Answer 1

1

You can use np.r_ to concatenate slice objects:

newarr [:,:,1:10] = oldarr[:,:,np.r_[1:7,8:11]] 

Example:

np.r_[1:4,6:8]
array([1, 2, 3, 6, 7])
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.