'Array values from list containing indices using Python
I would like to get array values of A based on indices mentioned in list B. The desired output is attached.
import numpy as np
A=np.array([[1,2,3],[4,5,6],[7,8,9]])
B=[(0,0),(1,0),(2,1),(2,2)]
The desired output should look like
[1,4,8,9]
Solution 1:[1]
The first step of the trick to be used here is:
- create a Numpy array from B,
- transpoose it,
- convert to a tuple of tuples.
The code to do it is:
tuple(map(tuple, np.array(B).T))
For your source data the result is:
((0, 1, 2, 2), (0, 0, 1, 2))
The first inner tuple contains row indices, the second - column indices.
Then you can use it to retrieve indicated elements of A, using A[…].
So the whole code to get your expected elements is:
A[tuple(map(tuple, np.array(B).T))]
Another, shorter option is:
A[tuple(np.array(B).T)]
This time tuple(np.array(B).T) yields a tuple, made of 1-D Numpy
arrays, made of rows of np.array(B).T.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
