Home  >  Article  >  Backend Development  >  How to Index One Numpy Array by Another?

How to Index One Numpy Array by Another?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 02:24:01599browse

How to Index One Numpy Array by Another?

Indexing One Array by Another in Numpy

Consider two matrices, A and B, where A contains arbitrary values and B holds indices of elements in A. The task is to extract elements from A based on the indices specified by B. This indexing allows for selective element retrieval.

Solution using Advanced Indexing:

Numpy's advanced indexing enables this operation using the expression:

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

This approach utilizes a combination of row indices and column indices retrieved from B to retrieve elements in A.

Solution using Linear Indexing:

An alternative approach involves linear indexing:

m, n = A.shape
out = np.take(A, B + n*np.arange(m)[:,None])

Here, m and n represent the dimensions of A, and the operations within the np.take() function ensure correct indexing of elements based on B.

Example:

Let's illustrate these solutions with an example:

import numpy as np

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

B = np.array([[0, 0, 1, 2],
              [0, 3, 2, 1],
              [3, 2, 1, 0]])

# Advanced indexing
result1 = A[np.arange(A.shape[0])[:,None], B]

# Linear indexing
m, n = A.shape
result2 = np.take(A, B + n*np.arange(m)[:,None])

print("Result using advanced indexing:")
print(result1)

print("Result using linear indexing:")
print(result2)

Output:

Result using advanced indexing:
[[2 2 4 5]
 [1 9 8 6]
 [2 0 7 8]]

Result using linear indexing:
[[2 2 4 5]
 [1 9 8 6]
 [2 0 7 8]]

The above is the detailed content of How to Index One Numpy Array by Another?. 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