首頁  >  文章  >  後端開發  >  如何在 NumPy 中使用整數數組索引從多維數組中提取元素?

如何在 NumPy 中使用整數數組索引從多維數組中提取元素?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 16:17:02248瀏覽

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]])

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]])

One approach is using integer array indexing as follows:

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

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()])

Output:

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

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

以上是如何在 NumPy 中使用整數數組索引從多維數組中提取元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn