Numpy submatrix 3D using a single indexing element

I have a 3D numpy array:

K = (np.arange(36)).reshape((4,3,3))+1
[[[ 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]]]

where each element in K is a matrix. Now I want to get the whole 2D submatrix using a specific index vector

I know this is possible as follows:

idx = np.s_[:,:2,:2]
K_sub = K[idx]
[[[ 1  2]
[ 4  5]]

[[10 11]
[13 14]]

[[19 20]
[22 23]]

[[28 29]
[31 32]]]

The problem is that I want to use an arbitrary indexing array and not slice to select rows and columns.

In addition, I want to use a single object to get a list of submatrices, for example:

K_sub = [magic_indexing]

and not:

K_sub = np.array([k_[train][:,train] for k_ in K])

Is there an easy way to do this?

+4
source share
1 answer

, , np.ix_ , , advanced-indexing, -

K[np.ix_(np.arange(K.shape[0]), train, train)]
0

Source: https://habr.com/ru/post/1663794/


All Articles