"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-08
Browse:221

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]
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3