3

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]])
McManip
  • 155
  • 1
  • 9
  • 1
    [This answer](https://stackoverflow.com/a/3912120/567595) is helpful for converting slice notation into a tuple that can be stored. e.g. you could say `SLICE_Z = slice(None, None, None), 2` then `z = data[SLICE_Z]` – Stuart Oct 05 '18 at 22:41
  • `np.s_` and `np.r_` may also be useful. – hpaulj Oct 05 '18 at 22:46

1 Answers1

2
SLICE_Z = 2

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

stackPusher
  • 6,076
  • 3
  • 35
  • 36