Extracting Elements from a 2D Array Using Indices from Another Array
In NumPy, sometimes it becomes necessary to extract specific elements from a multidimensional array based on indices stored in another array. This scenario often arises when working with data structures such as sparse matrices or indexed selections.
Problem:
Consider two NumPy arrays:
A = np.array([[0, 1], [2, 3], [4, 5]]) B = np.array([[1], [0], [1]]) # Index array
The goal is to extract one element from each row of A, where the specific element is specified by the index in the corresponding row of B. The expected output should be:
C = np.array([[1], [2], [5]])
Solutions:
1. Purely Integer Array Indexing:
A[np.arange(A.shape[0]), B.ravel()]
This method involves using NumPy's integer array indexing capabilities. It generates a range of indices corresponding to the rows of A and combines it with the flattened B array to select the appropriate elements.
2. Transposing and np.choose:
np.choose(B.ravel(), A.T)
In this alternative approach, you transpose A to match the shape of B and then use np.choose to select the desired elements based on the flattened B array.
3. Iterable Unpacking (Python >=3.6):
*A = A.T C = np.array([*zip(*A)][i] for i in B.ravel())
This method uses iterable unpacking to convert A to a list of rows and then iterates over the rows of A based on the indices in B to extract the desired elements.
4. List Comprehensions and Broadcasting:
[A[i][j] for i, j in zip(range(A.shape[0]), B.ravel())]
List comprehensions can be used to create a new array by iterating over the elements of A and B and performing the element-wise selection.
5. Fancy Indexing (NumPy >=1.18):
A[np.stack([range(A.shape[0]), B.ravel()], axis=1)]
Fancy indexing allows for more efficient and compact indexing operations. In this case, it creates a 2D array with the row indices and B indices, which can be used to select the desired elements from A.
The most appropriate solution depends on the specific requirements and constraints of the task, such as efficiency, readability, and compatibility with older versions of NumPy.
The above is the detailed content of How to Extract Elements from a 2D NumPy Array Using Indices from Another Array?. For more information, please follow other related articles on the PHP Chinese website!