Utilizing Integer Array Indexing to Extract Elements Based on Secondary Array Indices
In the given scenario, the goal is to retrieve specific elements from an array A using indices specified in a second array B. Instead of relying on np.take or np.choose, a more straightforward approach is to employ NumPy's integer array indexing:
A[np.arange(A.shape[0]),B.ravel()]
Here's how this code achieves the desired result:
This approach is particularly useful when B is a 1D array or a list of column indices. By skipping the flattening operation, the code becomes even simpler:
A[np.arange(A.shape[0]),B]
Example:
A = np.array([[0, 1], [2, 3], [4, 5]]) B = np.array([1, 0, 1]) result = A[np.arange(A.shape[0]), B] print(result) # Output: [1, 2, 5]
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3