Home >Backend Development >Python Tutorial >How to Index Multiple Arrays in NumPy?

How to Index Multiple Arrays in NumPy?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 00:34:021044browse

How to Index Multiple Arrays in NumPy?

Indexing Multiple Arrays in NumPy

In NumPy, indexing beyond single-dimensional arrays requires advanced techniques. One scenario is indexing one array based on the values of another array, known as multidimensional indexing.

Consider matrices A with arbitrary values:

array([[ 2, 4, 5, 3],
       [ 1, 6, 8, 9],
       [ 8, 7, 0, 2]])

And matrix B containing indices of elements in A:

array([[0, 0, 1, 2],
       [0, 3, 2, 1],
       [3, 2, 1, 0]])

To select values from A using the indices in B, you can employ NumPy's advanced indexing:

A[np.arange(A.shape[0])[:,None],B]

This indexing approach combines the row indices (0, 1, 2) with the indices specified in B.

Alternatively, you can use linear indexing:

m,n = A.shape
out = np.take(A,B + n*np.arange(m)[:,None])

Here, m and n represent the number of rows and columns in A, respectively. np.take() extracts elements from A based on the linear indices generated by the sum of B and n multiplied by the range of row indices.

Using either technique, the output will be:

[[2, 2, 4, 5],
 [1, 9, 8, 6],
 [2, 0, 7, 8]]

This indexing method provides flexibility in accessing and manipulating elements based on multiple criteria, enhancing the versatility of NumPy arrays for complex data processing scenarios.

The above is the detailed content of How to Index Multiple Arrays in NumPy?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn