Home  >  Article  >  Backend Development  >  How to Access Array Elements in NumPy Using Indices from Another Array?

How to Access Array Elements in NumPy Using Indices from Another Array?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 02:03:02669browse

How to Access Array Elements in NumPy Using Indices from Another Array?

Accessing Array Elements using Array Indices in NumPy

NumPy's indexed functions provide powerful data manipulation techniques, including the ability to select elements from one array using indices specified by another array. To achieve this:

Approach 1: Using Advanced Indexing

A[np.arange(A.shape[0])[:,None],B]<br>

This code leverages advanced indexing, where np.arange(A.shape[0])[:,None] creates a column vector with indices for each row in A. Combining this with B allows indexing A along both rows and columns.

Approach 2: Linear Indexing

m,n = A.shape<br>np.take(A,B   n*np.arange(m)[:,None])<br>

This approach utilizes linear indexing, where each element in A is addressed by a single index. It first calculates a linear index by adding the corresponding row from B to a linear sequence generated using np.arange. This linear index is then used to retrieve elements from A.

Sample Usage:

Given matrix A:

array([[ 2, 4, 5, 3],
       [ 1, 6, 8, 9],
       [ 8, 7, 0, 2]])

And index matrix B:

array([[0, 0, 1, 2],
       [0, 3, 2, 1],
       [3, 2, 1, 0]])

Applying the approaches yields the desired result:

array([[2, 2, 4, 5],
       [1, 9, 8, 6],
       [2, 0, 7, 8]])

The above is the detailed content of How to Access Array Elements in NumPy 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