Indexing One Array by Another in NumPy
In scientific computing, manipulating multidimensional arrays is a common task. NumPy's advanced indexing capabilities provide a powerful tool for complex indexing operations, making it easy to extract data from an array based on index values stored in another array.
Consider a matrix A with arbitrary values and a matrix B containing indices of elements in A. The task is to select values from A pointed by B, resulting in a matrix C.
One approach to achieve this is through NumPy's advanced indexing:
C = A[np.arange(A.shape[0])[:, None], B]
This approach operates efficiently on large arrays without the need for loops.
Linear indexing provides another method for this operation:
m, n = A.shape C = np.take(A, B + n * np.arange(m)[:, None])
Both advanced indexing and linear indexing offer efficient methods to index one array by another in NumPy.
The above is the detailed content of How to Index One NumPy Array by Another: Advanced Indexing vs. Linear Indexing?. For more information, please follow other related articles on the PHP Chinese website!