0

Can anyone explain why the results below are different? In one case I specify :2 which should be equivalent to [0,1], but it is unexpectedly not.

x = np.array([[[1,2,3],[4,5,6],[7,8,9]]])
array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]])

x.shape
(1, 3, 3)

# Works as expected
x[0, :, :2]
array([[1, 2],
       [4, 5],
       [7, 8]])

# Not as expected, the results got transposed
x[0, :, [0,1]]
array([[1, 4, 7],
       [2, 5, 8]])
David Parks
  • 30,789
  • 47
  • 185
  • 328
  • It's the slice in the middle - it's a case of mixed basic and advanced indexing. – hpaulj May 02 '19 at 19:53
  • If you want to retain the shape in the last dimension, use `x[..., :2]`. If you mix and match advanced indexing and basic slicing, that's what you'll get.. – kmario23 May 02 '19 at 20:02
  • 1
    https://stackoverflow.com/q/53841497/901925 – hpaulj May 02 '19 at 20:03
  • Here's a post which explains in detail: [why-using-an-array-as-an-index-changes-the-shape-of-a-multidimensional-ndarray](https://stackoverflow.com/questions/55829631/why-using-an-array-as-an-index-changes-the-shape-of-a-multidimensional-ndarray/55830708#55830708) – kmario23 May 02 '19 at 20:05
  • Thanks for the references, those do answer the question, I've voted this a duplicate now. Much appreciated. – David Parks May 02 '19 at 20:11

0 Answers0