3

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]

2
  • Is this always a diagonal, or is this just an example? Commented Mar 2, 2020 at 11:19
  • You need to convert the list to a tuple of lists, one for each dimension ([0,1,2,3],[0,1,2,3]) Commented Mar 2, 2020 at 16:11

3 Answers 3

3

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])
Sign up to request clarification or add additional context in comments.

Comments

3

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]

Comments

0

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]).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.