Home  >  Article  >  Backend Development  >  How to Extract Elements from a 2D Array Using Indices from Another Array?

How to Extract Elements from a 2D Array Using Indices from Another Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 11:40:021030browse

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:

  • np.arange(A.shape[0]) creates an array containing indices for each row of A.
  • B.ravel() flattens B, removing any additional dimensions.
  • The combined index array [np.arange(A.shape[0]),B.ravel()] specifies the row and column indices in A to extract.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn