Home  >  Article  >  Backend Development  >  How to Extract Elements from an Array Based on Indices in Another Array Using Integer Array Indexing?

How to Extract Elements from an Array Based on Indices in Another Array Using Integer Array Indexing?

Linda Hamilton
Linda HamiltonOriginal
2024-11-09 02:55:02799browse

How to Extract Elements from an Array Based on Indices in Another Array Using Integer Array Indexing?

Utilizing Integer Array Indexing to Extract Elements Based on Secondary Array Indices

In the given scenario, the goal is to retrieve specific elements from an array A using indices specified in a second array B. Instead of relying on np.take or np.choose, a more straightforward approach is to employ NumPy's integer array indexing:

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

Here's how this code achieves the desired result:

  • np.arange(A.shape[0]) creates an array of indices from 0 to (A.shape[0] - 1), representing the rows of A.
  • B.ravel() flattens B into a one-dimensional array, ensuring that it has the same number of elements as rows in A.
  • The indexing operation A[...] retrieves elements from A using the row indices and column indices from B.

This approach is particularly useful when B is a 1D array or a list of column indices. By skipping the flattening operation, the code becomes even simpler:

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

Example:

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

result = A[np.arange(A.shape[0]), B]

print(result)
# Output: [1, 2, 5]

The above is the detailed content of How to Extract Elements from an Array Based on Indices in Another Array Using Integer Array 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