Home > Backend Development > Python Tutorial > How to Extract Elements from a Multidimensional Array Using Integer Array Indexing in NumPy?

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

Mary-Kate Olsen
Release: 2024-11-15 16:17:02
Original
340 people have browsed it

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

Extracting Elements Using Integer Array Indexing

When working with multidimensional arrays, it's often necessary to extract specific elements based on indices. In NumPy, you can use various techniques to achieve this. One such method is by employing integer array indexing.

Consider the following example:

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

Our goal is to create a new array C that contains elements from A where the row index for each element is given by A.shape[0] and the column index is given by the raveled version of B. In other words, C should be:

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

One approach is using integer array indexing as follows:

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

This approach uses the arange function to generate a range of indices for the rows of A and then combines it with the raveled version of B to create the column indices. The result is a new array containing the desired elements.

# 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

It's important to note that if B is a 1D array or a list, you can skip the flattening operation with .ravel().

The above is the detailed content of How to Extract Elements from a Multidimensional Array Using Integer Array Indexing in NumPy?. 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