I have an np.array data
of shape (28,8,20), and I only need certain entries from it, so I'm taking a slice:
In [41]: index = np.array([ 5, 6, 7, 8, 9, 10, 11, 17, 18, 19])
In [42]: extract = data[:,:,index]
In [43]: extract.shape
Out[43]: (28, 8, 10)
So far so good, everything as it should be. But now I wand to look at just the first two entries on the last index for the first line:
In [45]: extract[0,:,np.array([0,1])].shape
Out[45]: (2, 8)
Wait, that should be (8,2). It switched the indices around, even though it did not when I sliced the last time! According to my understanding, the following should act the same way:
In [46]: extract[0,:,:2].shape
Out[46]: (8, 2)
... but it gives me exactly what I wanted! As long as I have a 3D-array, though, both methods seem to be equivalent:
In [47]: extract[:,:,np.array([0,1])].shape
Out[47]: (28, 8, 2)
In [48]: extract[:,:,:2].shape
Out[48]: (28, 8, 2)
So what do I do if I want not just the first two entries but an irregular list? I could of course transpose the matrix after the operation but this seems very counter-intuitive.
A better solution to my problem is this (though there might be a more elegant one):
In [64]: extract[0][:,[0,1]].shape
Out[64]: (8, 2)
Which brings us to the actual
question:
I wonder what the reason for this behaviour is? Whoever decided that this is how it should work probably knew more about programming than I do and thought that this is consistent in some way that I am entirely missing. And I will likely keep hitting my head on this unless I have a way to make sense of it.
See Question&Answers more detail:
os