5

If I have a 2D numpy array that I want to extract elements using a list of row,col index pairs.

xy = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
idx = np.array([[0, 0], [1, 1], [2, 2]])

The for loop solution:

elements = list()
for i in idx:
    elements.append(xy[idx[i][0], xy[idx[i][1])

Output:

print(elements)
>> [1, 5, 9]

I found the solution if there idx is a list of tuples but I hoping for a solution where there is no need to convert the idx to tuples first.

4
  • Numpy has the take method for 1d indices, but still thinking on how to modify my arrays to work with it? (if it is even the right solution) Commented Mar 13, 2017 at 22:59
  • I'm confused, this was marked as duplicate, but the linked question is converting the indexes to tuples (which is what I'm trying to avoid). Commented Mar 13, 2017 at 23:15
  • Hooray, found the answer. Since I can't add an answer here. the solution is just use slicing: element = xy[[idx[:,0], idx[:,1]] Commented Mar 13, 2017 at 23:24
  • The accepted answer to the linked dup question has discussed using slices : a[idx[:,0],idx[:,1],idx[:,2]]. We just need to read the entire posts :) Commented Mar 14, 2017 at 8:11

1 Answer 1

2
    idy = zip(*idx)
    output = xy[idy]
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't zip converting idx to a list of tuples (using a loop)?
looking at zip here it is just using loops.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.