Home > Backend Development > Python Tutorial > 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
Release: 2024-11-09 02:55:02
Original
864 people have browsed it

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()]
Copy after login

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]
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template