[Numpy-discussion] Slice specified axis

Tony Yu tsyu80@gmail....
Mon Apr 9 22:11:49 CDT 2012

```On Mon, Apr 9, 2012 at 12:22 PM, Benjamin Root <ben.root@ou.edu> wrote:

>
>
> On Mon, Apr 9, 2012 at 12:14 PM, Jonathan T. Niehof <jniehof@lanl.gov>wrote:
>
>> On 04/06/2012 06:54 AM, Benjamin Root wrote:
>>
>> > 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.
>>
>> List of slice(None), correct? At least that's what I see in the source,
>> and:
>>
>>  >>> a = numpy.array([[1,2],[3,4]])
>>  >>> operator.getitem(a, (None, slice(1, 2)))
>> array([[[3, 4]]])
>>  >>> operator.getitem(a, (slice(None), slice(1, 2)))
>> array([[2],
>>        [4]])
>>
>>
> Correct, sorry, I was working from memory.
>
> Ben Root
>
>
I guess I wasn't reading very carefully and assumed that you meant a list
of `slice(None)` instead of a list of `None`. In any case, both your
solution and Matthew's solution work (and both are more readable than my
original implementation).

After I got everything cleaned up (and wrote documentation and tests), I
found out that numpy already has a function to do *exactly* what I wanted
in the first place: `np.split` (the slicing was just one component of
this). I was initially misled by the
docstring<https://github.com/numpy/numpy/pull/249>,
but with a list of indices, you can split an array into subarrays of
variable length (I wanted to use this to save and load ragged arrays).
Well, I guess it was a learning experience, at least.

In case anyone is wondering about the original question, `np.split` (and
`np.array_split`) uses `np.swapaxes` to specify the slicing axis.