Reputation: 2941
I have a multidimensional array of this shape:
(2, 200, 2, 3, 3, 114)
I would like to extract a specific set of values from it using this command:
pab[0][:][0][0][0][i]
So basically I need each value iterated over the second dimension for fixes values in the first, third, fourth, and fifth. The last dimension is in a loop.
However, it appears my way of slicing and wanting to extract over the second dimension does not work properly. After some investigation I found out that the shape does not change as expected. It appears I did not understand it correctly:
>>> pab.shape
(2, 200, 2, 3, 3, 114)
>>> pab[0].shape
(200, 2, 3, 3, 114)
>>> pab[0][:].shape
(200, 2, 3, 3, 114)
>>> pab[0][:][0].shape
(2, 3, 3, 114) # I would have expected to see (200, 3, 3, 114)
>>> pab[0][:][0][0].shape
(3, 3, 114)
I found some articles talking about multidimensional slicing but none of them explained this behavior or I misunderstood them.
If someone can explain why the shape of the array changes as shown and not as expected to (200, 3, 3, 114)
and also what the proper way would be I would highly appreciate this! In the end I was trying to get an array of shape (200, )
Upvotes: 1
Views: 72
Reputation: 231540
Indexing numpy
with arr[i][j]...
works with all scalars, but not with slices. [:]
does nothing. (Even with a list [:]
just makes a copy.). So you want to combine the indexes into one expression:
In [40]: arr = np.ones((2, 200, 2, 3, 3, 114),int)
In [41]: arr.shape
Out[41]: (2, 200, 2, 3, 3, 114)
In [42]: arr[0].shape
Out[42]: (200, 2, 3, 3, 114)
In [43]: arr[0,:,0,0].shape
Out[43]: (200, 3, 114)
In [44]: arr[0,:,0,0,0,3].shape
Out[44]: (200,)
Putting a slice in the middle like this can produce unexpected results:
In [45]: arr[0,:,0,0,0,[1,2]].shape
Out[45]: (2, 200)
In [47]: arr[0][:,0,0,0,[1,2]].shape
Out[47]: (200, 2)
Here the size 200 slice has moved to the end. This an awkward case of mixed basic and advanced indexing. https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing
Upvotes: 1