Get values from numpy 2d array by using a list of tuples as indexes

Viewed 1110

I have a list of tuples: [(0,0), (1,1), (2,2), (3,3), (4,4)] And I have my 2d numpy array:

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

How can I get the values from the 2d array located by using the positions from the list with numpy? I should get the diagonal: [8,9,8,1,5]

3 Answers

Try this,

>>> import numpy as np
>>> req_index = [(0,0), (1,1), (2,2), (3,3), (4,4)] # this is your tuple index list
>>> arr = np.array([[8, 6, 5, 9, 3],
       [7, 9, 7, 9, 1],
       [2, 1, 8, 8, 6],
       [7, 1, 5, 1, 3],
       [6, 7, 1, 1, 5]])
>>> 

Output:

>>> [arr[i][j] for i, j in req_index]
[8, 9, 8, 1, 5]

You can transpose the list of tuples, and pass these as items in a tuple:

>>> b = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> a[tuple(np.transpose(b))]
array([8, 9, 8, 1, 5])

Here's one way to do this:

 a=np.array([[8, 6, 5, 9, 3],
   [7, 9, 7, 9, 1],
   [2, 1, 8, 8, 6],
   [7, 1, 5, 1, 3],
   [6, 7, 1, 1, 5]])

np.diag(a)

prints array([8, 9, 8, 1, 5]).

Related