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

Mary-Kate Olsen
發布: 2024-11-15 16:17:02
原創
247 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板