[Numpy-discussion] Slice specified axis

Matthew Brett matthew.brett@gmail....
Fri Apr 6 15:25:03 CDT 2012


Hi,

On Fri, Apr 6, 2012 at 1:12 PM, Tony Yu <tsyu80@gmail.com> wrote:
>
>
> On Fri, Apr 6, 2012 at 8:54 AM, Benjamin Root <ben.root@ou.edu> wrote:
>>
>>
>>
>> On Friday, April 6, 2012, Val Kalatsky wrote:
>>>
>>>
>>> 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
>>
>>
>> Take a peek at how np.gradient() does it.  It creates a list of None with
>> a length equal to the number of dimensions, and then inserts a slice object
>> in the appropriate spot in the list.
>>
>> Cheers!
>> Ben Root
>
>
> Hmm, it looks like my original implementation wasn't too far off. Thanks for
> the tip!

Another option:

me_first = np.rollaxis(arr, axis)
slice = me_first[start:end]
slice = np.rollaxis(slice, 0, axis+1)

Best,

Matthew


More information about the NumPy-Discussion mailing list