Home > Backend Development > Python Tutorial > 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
Release: 2024-11-12 18:04:02
Original
807 people have browsed it

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

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

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

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

Output:

[[0 1]
 [2 3]
 [4 5]]
[[1]
 [0]
 [1]]
[1 2 5]
Copy after login

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!

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