2

Given a numpy array x of shape (N_1...N_k) where k is arbitrary, and 2 arrays :

start_indices=[a_1,...,a_k], end_indices=[b_1,...b_k], where `0<=a_i<b_i<=N_i`.

I want to slice x as follows: x[a_1:b_1,...,a_k:b_k].

Lets say :

x is of shape `(1000, 1000, 1000)`
start_indices=[450,0,400]
end_indices=[550,1000,600].

I want the output to be equal x[450:550,0:1000,400:600].

For example I tried to define :

slice_arrays = (np.arange(start_indices[i], end_indices[i]) for i in range(k))

and use

x[slice_arrays]

but it didn't work.

1
  • arange creates arrays, which index in a different way. Commented May 21, 2019 at 15:25

1 Answer 1

3

You can use slice notation to create an indexing tuple that could be used for the indexing -

indexer = tuple([slice(i,j) for (i,j) in zip(start_indices,end_indices)])
out = x[indexer]

Alternatively, with shorthand np.s_ -

indexer = tuple([np.s_[i:j] for (i,j) in zip(start_indices,end_indices)])

Or with map for a compact one -

indexer = tuple(map(slice,start_indices,end_indices))
Sign up to request clarification or add additional context in comments.

3 Comments

It worked thanks! I tried the exact same thing with just with array instead of tuple and it did not worked but this seems to fix it!
np.s_ is not really a shorthand here, is it? ;^)
@PaulPanzer Nah, isn't saving any characters here.

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.