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