Numpy uses multiple indexing, so instead of A[1][2][3] you can - and should - use A[1,2,3] .
Then you might think that you can do A[:, second, third] , but the numpy indices are passed, and the second and third broadcasts (two one-dimensional sequences) end as the numpy-equivalent zip , so the result has the form (5, 2) .
What you really want is to index, in fact, the second and third external product. You can do this using translation by doing one of them, say second into a two-dimensional array with the form (2.1). Then the form that occurs as a result of the translation of second and third is (2,2) .
For example:
In [8]: import numpy as np In [9]: a = np.arange(125).reshape(5,5,5) In [10]: second = [1,2] In [11]: third = [3,4] In [12]: s = a[:, np.array(second).reshape(-1,1), third] In [13]: s.shape Out[13]: (5, 2, 2)
Note that in this particular example, the values ββin second and third are sequential. If this is typical, you can simply use slices:
In [14]: s2 = a[:, 1:3, 3:5] In [15]: s2.shape Out[15]: (5, 2, 2) In [16]: np.all(s == s2) Out[16]: True
There are a couple of very important differences in these two methods.
- The first method will also work with indexes that are not equivalent to slices. For example, it will work if
second = [0, 2, 3] . (Sometimes you will see this indexing style called fancy indexing.) - In the first method (using broadcast and "fantastic indexing"), the data is a copy of the original array. In the second method (using only slices), the
s2 array is a representation in the same memory block as a . Changes in place in one will change them both.
Warren weckesser
source share