1
data = np.zeros((5, 16, 16))

I would like to access a slice of size 1 of this numpy data array. It might be helpful to define what I don't want:

>>> data[2].shape
(16, 16)

Instead, I want to keep the dimensionality the same. A couple of ways come to mind here:

>>> np.expand_dims(data[2], 0).shape
(1, 16, 16)

>>> data[2:3].shape
(1, 16, 16)

>>> data[None, 2].shape
(1, 16, 16)

Which one of these options is more pythonic, or is there a better solution here?

sshashank124
  • 31,495
  • 9
  • 67
  • 76
EliteKaffee
  • 109
  • 1
  • 2
  • 12
  • 2
    `result = data[2:3]` seems the simplest approach to me, since you're just slicing along the first axis which is what you want – yatu Jan 14 '20 at 12:06
  • true, the intuition is good here. My main problem with this solutions is readability - I feel like the form does suggest a different function and at first glance, it is not obvious that this results in a singleton dimension – EliteKaffee Jan 14 '20 at 12:15
  • I favor the slice, since it's more obvious that you are trying to preserve an existing dimension. – hpaulj Jan 14 '20 at 12:38

1 Answers1

1

You can also do it with a list of indices with a single element:

>>> data[[2]].shape
(1, 16, 16)

As for which is more pythonic, that is more opinion-based than anything.


Note: This method will create a copy of the data instead of a view into the same data since arbitrary indices might not result in a contiguous view. This is explained in detail in the question Avoid copying when indexing a numpy arrays using lists

sshashank124
  • 31,495
  • 9
  • 67
  • 76