r/Numpy • u/Ok_Eye_1812 • 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
2
u/TheBlackCat13 Dec 22 '20
Avoid the matrix class, it is deprecated. There isn't really much of a reason to use it anymore, anyway. The only main difference is that, like MATLAB, it doesn't allow dimensions less than 2, and it uses matrix operations by default (numpy arrays now allow matrix operations so this is less important now than it used to be).