Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a numpy array along a dynamically specified axis

Tags:

python

numpy

I would like to dynamically slice a numpy array along a specific axis. Given this:

axis = 2 start = 5 end = 10 

I want to achieve the same result as this:

# m is some matrix m[:,:,5:10] 

Using something like this:

slc = tuple(:,) * len(m.shape) slc[axis] = slice(start,end) m[slc] 

But the : values can't be put in a tuple, so I can't figure out how to build the slice.

like image 446
Sean Mackesey Avatar asked Jun 25 '14 01:06

Sean Mackesey


2 Answers

As it was not mentioned clearly enough (and i was looking for it too):

an equivalent to:

a = my_array[:, :, :, 8] b = my_array[:, :, :, 2:7] 

is:

a = my_array.take(indices=8, axis=3) b = my_array.take(indices=range(2, 7), axis=3) 
like image 75
Śmigło Avatar answered Sep 16 '22 11:09

Śmigło


I think one way would be to use slice(None):

>>> m = np.arange(2*3*5).reshape((2,3,5)) >>> axis, start, end = 2, 1, 3 >>> target = m[:, :, 1:3] >>> target array([[[ 1,  2],         [ 6,  7],         [11, 12]],         [[16, 17],         [21, 22],         [26, 27]]]) >>> slc = [slice(None)] * len(m.shape) >>> slc[axis] = slice(start, end) >>> np.allclose(m[slc], target) True 

I have a vague feeling I've used a function for this before, but I can't seem to find it now..

like image 36
DSM Avatar answered Sep 17 '22 11:09

DSM