[Numpy-discussion] Slice specified axis

Val Kalatsky kalatsky@gmail....
Thu Apr 5 23:58:20 CDT 2012


The only slicing short-cut I can think of is the Ellipsis object, but it's
not going to help you much here.
The alternatives that come to my mind are (1) manipulation of shape
directly and (2) building a string and running eval on it.
Your solution is better than (1), and (2) is a horrible hack, so your
solution wins again.
Cheers
Val

On Thu, Apr 5, 2012 at 2:52 PM, Tony Yu <tsyu80@gmail.com> wrote:

> Is there a way to slice an nd-array along a specified axis? It's easy to
> slice along a fixed axis, e.g.:
>
> axis = 0:
> >>> array[start:end]
>
> axis = 1:
> >>> array[:, start:end]
> ...
>
> But I need to do this inside of a function that accepts arrays of any
> dimension, and the user can operate on any axis of the array. My current
> solution looks like the following:
>
> >>> aslice = lambda axis, s, e: (slice(None),) * axis + (slice(s, e),)
> >>> array[aslice(axis, start, end)]
>
> which works, but I'm guessing that numpy has a more readable way of doing
> this that I've overlooked.
>
> Thanks,
> -Tony
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20120405/529aa722/attachment-0001.html 


More information about the NumPy-Discussion mailing list