0

I am attempting to slice a Numpy array by an array of indices. For example,

 array = [10,15,20,25,32,66]
 indices = [1,4,5]

The optimal output would be

[[10][15,20,25,32][66]]

I have tried using

 array[indices]

but this just produces the single values of each individual index rather than all those in between.

5
  • What exactly do your three indices in the array represent. I do not really understand how you get to your desired output from the given input. Commented Feb 2, 2017 at 15:26
  • The indices are obtained by np.where(). So basically the indices, 1,4,5, would slice the array like so: 0:1, 1:4, 4:5 Commented Feb 2, 2017 at 15:28
  • What you call "optimal output" cannot be the product of a slicing operation, because it has an undefined shape. Commented Feb 2, 2017 at 15:29
  • @TrevorJudice Then why is the last output result 66 and not 32? Commented Feb 2, 2017 at 15:29
  • ImportanceOfBeingErnest is correct. What you could get is a list containing the slices that you wanted to have. Also as Mitch was saying the last element of your desired output does not match your way of constructing it. Commented Feb 2, 2017 at 15:30

2 Answers 2

4

Consider using np.split, like so

array = np.asarray([10, 15, 20, 25, 32, 66])
indices = [1, 5]

print(np.split(array, indices))

Produces

[array([10]), array([15, 20, 25, 32]), array([66])]

As split uses breakpoints only, where the index indicates the points at which to break blocks. Hence, no need to indicate 1:4, this is implicitly defined by breakpoints 1, 5.

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

2 Comments

What a useful little function this np.split! If only it could do multiple axes.
This is what I wanted. Thank you.
1

According to your comment this generator produces the desired result:

def slice_multi(array, indices):
    current = 0
    for index in indices:
        yield array[current:index]
        current = index

array = [10,15,20,25,32,66]
indices = [1,4,5]
list(slice(array, indices)) # [[10], [15, 20, 25], [32]]

4 Comments

It does when you take his comment into account where he states, that the last slice should be array[4:5] which is indeed [32].
This produces the result of slicing [0:1], [1:4], [4:5], as stated in the comment. I just produced the solution which fit the comment, since it's different from the one stated in the original question.
numpy.split(array, indices)[-1] is probably easier, though.
But that's exactly what np.array_slice does - iteratively slice along the desired axis and return a list of arrays. Look at it's code. It's not compiled.

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.