How can I provide syntactic sugar for slicing a numpy array?

518 views Asked by At

I would like to write more readable code by doing something like:

import numpy as np

SLICE_XY = slice(0, 2)
SLICE_Z = slice(2, 3)

data = np.array([[0, 1, 2],
                 [3, 4, 5],
                 [6, 7, 8],
                 [9, 10, 11]])

xy = data[:, SLICE_XY]
z = data[:, SLICE_Z]

However, I have run into the issue that doing the above produces

>>> xy
array([[ 0,  1],
       [ 3,  4],
       [ 6,  7],
       [ 9, 10]])
>>> z
array([[ 2],
       [ 5],
       [ 8],
       [11]])

which is what I expected for xy. But for z I expected it to be equivalent to

>>> data[:, 2]
array([ 2,  5,  8, 11])

Note:

>>> data[:, 0:2]
array([[ 0,  1],
       [ 3,  4],
       [ 6,  7],
       [ 9, 10]])
1

There are 1 answers

0
stackPusher On BEST ANSWER
SLICE_Z = 2

By design, arr[0:1] is not the same as arr[0]. Slices always return iterables.