Search code examples
numpysub-array

How to get a subarray in numpy


I have an 3d array and I want to get a sub-array of size (2n+1) centered around an index indx. Using slices I can use

y[slice(indx[0]-n,indx[0]+n+1),slice(indx[1]-n,indx[1]+n+1),slice(indx[2]-n,indx[2]+n+1)]

which will only get uglier if I want a different size for each dimension. Is there a nicer way to do this.


Solution

  • You don't need to use the slice constructor unless you want to store the slice object for later use. Instead, you can simply do:

    y[indx[0]-n:indx[0]+n+1, indx[1]-n:indx[1]+n+1, indx[2]-n:indx[2]+n+1]
    

    If you want to do this without specifying each index separately, you can use list comprehensions:

    y[[slice(i-n, i+n+1) for i in indx]]