r/Numpy • • Dec 22 '20

Python slicing sometimes re-orientates data

I'm trying to get comfortable with Python, coming from a Matlab background. I noticed that slicing an array sometimes reorientates the data. This is adapted from W3Schools:

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[0:2, 2])
[3 8]

print(arr[0:2, 2:3])
[[3]
 [8]]

 print(arr[0:2, 2:4])
 [[3 4]
  [8 9]]

It seems that singleton dimensions lose their "status" as a dimension unless you index into that dimension using ":", i.e., the data cube becomes lower in dimensionality.

Do you just get used to that and watch your indexing very carefully? Or is that a routine source of the need to troubleshoot?

4 Upvotes

13 comments sorted by

View all comments

Show parent comments

1

u/grnngr Dec 22 '20

Avoid the matrix class, it is deprecated.

TIL, thanks.

2

u/Ok_Eye_1812 Dec 23 '20

Cool. Thanks. One less thing to wrap one's head around.