Home > Article > Backend Development > How to Extract Elements from a 2D Array Using Indices from Another Array?
Using NumPy Array as Indices for the 2nd Dimension of Another Array
To extract specific elements from a 2D array based on indices provided by a second array, you can leverage NumPy's integer array indexing.
Consider this example:
A = np.array([[0,1], [2,3], [4,5]]) B = np.array([[1], [0], [1]], dtype='int')
To obtain the following desired output:
C = np.array([[1], [2], [5]])
You can employ the following method:
A[np.arange(A.shape[0]),B.ravel()]
How it Works:
Alternatively, if B is a 1D array or a list of column indices, you can skip flattening with .ravel():
A[np.arange(A.shape[0]),B]
This method provides a straightforward approach for extracting elements from a 2D array using indices derived from another array.
The above is the detailed content of How to Extract Elements from a 2D Array Using Indices from Another Array?. For more information, please follow other related articles on the PHP Chinese website!