Sean Mackesey
Sean Mackesey

Reputation: 10939

Composing slices into a multidimensional slice for numpy array slicing

If I have two slice objects defined along one dimension each, is it possible to combine them to get a multidimensional slice object that can be used to slice a numpy array?

mat = np.zeros((10,10), dtype=np.uint8)
s1 = slice(0,5)
s2 = slice(0,5)
mat[s1,s2]  # I want to achieve this effect with one slice object    
slice2d = slice(s1, s2)  # does not throw an error
mat[slice2d]  # but this does not work

Upvotes: 2

Views: 473

Answers (1)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58865

As pointed out by @unutbu, what would be a multi-dimensional slice is actually a tuple or list of slice objects, then:

slice2d = (s1, s2)
mat[slice2d]

will work. Similarly, you can extend this to 3-D, ..., N-D arrays:

slice3d = (s1, s2, s3)
...
sliceNd = (s1, s3, s3, ..., sN)

Upvotes: 2

Related Questions