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')
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]])
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()]
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()])
Output:
[[0 1] [2 3] [4 5]] [[1] [0] [1]] [1 2 5]
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!