Home  >  Article  >  Backend Development  >  How to Extract Elements from a NumPy Array Using Integer Array Indexing?

How to Extract Elements from a NumPy Array Using Integer Array Indexing?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 18:04:02734browse

How to Extract Elements from a NumPy Array Using Integer Array Indexing?

Indexed Extraction with a NumPy Array

When working with multidimensional arrays in NumPy, it is often necessary to extract specific elements based on indices. In this regard, certain scenarios may arise where an array (B) serves as an index for the second dimension of another array (A).

Consider an example with two arrays A and B:

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

Our goal is to extract one element from each row of A, where the element index is determined by the corresponding element in B. The desired output is:

C = np.array([[1],
              [2],
              [5]])

Solution Using Integer Array Indexing:

Instead of broadcasting B, we can use NumPy's purely integer array indexing:

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

Here, np.arange(A.shape[0]) creates an array of indices corresponding to the number of rows in A, while B.ravel() flattens B into a 1D array. By combining these, we can extract the appropriate elements from A.

Sample Run:

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

Output:

[[0 1]
 [2 3]
 [4 5]]
[[1]
 [0]
 [1]]
[1 2 5]

This approach provides a concise and efficient solution to our extraction problem.

The above is the detailed content of How to Extract Elements from a NumPy 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