Home > Backend Development > Python Tutorial > 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
Release: 2024-11-09 11:40:02
Original
1069 people have browsed it

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')
Copy after login

To obtain the following desired output:

C = np.array([[1], [2], [5]])
Copy after login

You can employ the following method:

A[np.arange(A.shape[0]),B.ravel()]
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template