Home > Article > Backend Development > How to Extract Elements from an Array Based on Indices in Another Array Using Integer Array Indexing?
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]
The above is the detailed content of How to Extract Elements from an Array Based on Indices in Another Array Using Integer Array Indexing?. For more information, please follow other related articles on the PHP Chinese website!