Issue
Say I have a 2-D numpy array,
A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] # Shape: (3, 4)
and I have another 1-D array,
B = [0, 2, 1] # Shape: (3,)
I want to extract an element from the index of A's ith row corresponding to B's ith element. Meaning, if we consider the 3nd element in B, output will be 2nd element of 3rd row of A (that is, 9).
Thus, the desired output is:
C = [0, 6, 9]
Now, this can easily be done using a for loop
, however, I am looking for some other optimized ways of doing this.
I tried np.take()
, however it's not working as desired.
Solution
If your B array is the position along the second axis which you'd like for each element in the first axis, just provide a corresponding set of indices into the first dimension:
In [4]: A[range(A.shape[0]), B]
Out[4]: array([0, 6, 9])
This is equivalent to:
In [5]: A[[0, 1, 2], [1, 2, 0]]
Out[5]: array([0, 6, 9])
Answered By - Michael Delgado
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.