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.

dranobob
  • 796
  • 1
  • 5
  • 19
  • 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) – dranobob Mar 13 '17 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). – dranobob Mar 13 '17 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]] – dranobob Mar 13 '17 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 :) – Divakar Mar 14 '17 at 08:11

1 Answers1

2
    idy = zip(*idx)
    output = xy[idy]
Da Qi
  • 615
  • 5
  • 10