Home >Backend Development >Python Tutorial >How to Index One NumPy Array by Another: Advanced Indexing vs. Linear Indexing?

How to Index One NumPy Array by Another: Advanced Indexing vs. Linear Indexing?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 13:23:03487browse

How to Index One NumPy Array by Another: Advanced Indexing vs. Linear Indexing?

Indexing One Array by Another in NumPy

In scientific computing, manipulating multidimensional arrays is a common task. NumPy's advanced indexing capabilities provide a powerful tool for complex indexing operations, making it easy to extract data from an array based on index values stored in another array.

Consider a matrix A with arbitrary values and a matrix B containing indices of elements in A. The task is to select values from A pointed by B, resulting in a matrix C.

One approach to achieve this is through NumPy's advanced indexing:

C = A[np.arange(A.shape[0])[:, None], B]
  • np.arange(A.shape[0])[:, None]: Creates an array of row indices for A, with each column representing the same row index.
  • [:, None]: Expands the array to a 2D array with an extra dimension to align with B.

This approach operates efficiently on large arrays without the need for loops.

Linear indexing provides another method for this operation:

m, n = A.shape
C = np.take(A, B + n * np.arange(m)[:, None])
  • m, n = A.shape: Stores the dimensions of A.
  • B n * np.arange(m)[:, None]: Calculates the flattened index for each element in C based on the indices in B and the row number.
  • np.take(A, ...): Extracts elements from A using the flattened indices.

Both advanced indexing and linear indexing offer efficient methods to index one array by another in NumPy.

The above is the detailed content of How to Index One NumPy Array by Another: Advanced Indexing vs. Linear Indexing?. 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