Itaysason
Itaysason

Reputation: 31

Slicing NumPy array given start and end indices for generic dimensions

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.

Upvotes: 2

Views: 1035

Answers (1)

Divakar
Divakar

Reputation: 221564

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))

Upvotes: 3

Related Questions