I can't seeem to figure out how to slice an array so that I get the indices of interest in the 3rd dimension. Here is an example 3D numpy array.
data = np.arange(60).reshape(5,4,3)
print data
[[[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]]
[[12 13 14] [15 16 17] [18 19 20] [21 22 23]]
[[24 25 26] [27 28 29] [30 31 32] [33 34 35]]
[[36 37 38] [39 40 41] [42 43 44] [45 46 47]]
[[48 49 50] [51 52 53] [54 55 56] [57 58 59]]]
Now here are the indices that I would like to grab from the 3rd dimension.
indices_of_interest = np.random.randint(3, size=5) print indices_of_interest
[0 2 2 2 0]
So basically I want values
[[[ 0] [ 3] [ 6] [ 9]]
[[14] [17] [20] [23]]
[[26] [29] [32] [35]]
[[38] [41] [44] [47]]
[[48] [51] [54] [57]]]
Is there some way to do this? When I try and index the array directly it broadcasts the dimension rather than providing me a subset of the data.
We can use advanced-indexing
to grab them by the third dim -
data[np.arange(len(indices_of_interest)),:, indices_of_interest]
Sample run -
In [65]: data = np.arange(60).reshape(5,4,3)
In [66]: indices_of_interest = [0,2,2,2,0]
In [67]: data[np.arange(len(indices_of_interest)),:, indices_of_interest]
Out[67]:
array([[ 0, 3, 6, 9],
[14, 17, 20, 23],
[26, 29, 32, 35],
[38, 41, 44, 47],
[48, 51, 54, 57]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.