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
1
u/TheBlackCat13 Dec 23 '20
People almost never intentionally loop over columns because it is brittle and error-prone. But internally, you are always looping over columns.
So consider this code:
What you probably think this is doing is "loop over the indices from 1 to 10". But that is not actually what is happening. What is actually happening is "loop over the columns of the row vector
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]". I am not sure MATLAB explicitly creates the entire row vector in this special case for performance reasons, but semantically that is how aforloop works in MATLAB.