Reputation: 7
I need to extract certain values from a multidimensional array that are not subsequent.
import numpy as np
A = np.array([[[ 0., 4., 0. ],
[ 0.19230769, 4.03846154, 0. ],
[-0.4, 4.8, 0. ],
[ 2., 1., 0. ]],
[[ 1.2, 3.4, 0. ],
[ 2.11538462, 4.42307692, 0. ],
[ 0., 4., 0. ],
[ 3.6, 1.8, 0. ]],
[[ 1.8, 3.1, 0. ],
[ 3.17307692, 4.63461538, 0. ],
[ 0., 4., 0. ],
[ 4., 2., 0. ]]])
For every 4x3 block I want to extract an arbitrary row
For instance the following elements:
A[0,2,:]
A[1,1,:]
A[2,1,:]
So basicly the rowsB = [2,1,1]
, which would give me:
[-0.4 4.8 0. ]
[ 2.11538462 4.42307692 0. ]
[ 3.17307692 4.63461538 0. ]
How to do this efficiently?
Upvotes: 0
Views: 5583
Reputation: 879133
You could use "advanced indexing":
In [99]: A[[0,1,2], [2,1,1], :]
Out[99]:
array([[-0.4 , 4.8 , 0. ],
[ 2.11538462, 4.42307692, 0. ],
[ 3.17307692, 4.63461538, 0. ]])
Here the indexing arrays are
ind1 = [0, 1, 2]
ind2 = [2, 1, 1]
and since ind1
is indexing the first axis of A
and ind2
is indexing the second axis, and the third axis is getting fully sliced (with :
), the resulting array, result
, has the same shape as ind1
and ind2
-- i.e. (3,)
-- plus the shape of the fully sliced axis, which is also (3,)
. Thus, result.shape
is (3, 3)
and
result[i, j] = A[ind1[i], ind2[i], j]
for i = 0,1,2
and j = 0,1,2
.
Upvotes: 2