0

I have a pretty big numpy matrix (2-D array with more than 1000 * 1000 cells), and another 2-D array of indexes in the following form: [[x1,y1],[x2,y2],...,[xn,yn]], which is also quite large (n > 1000). I want to extract all the cells in the matrix that their (x,y) coordinates appear in the array as efficient as possible, i.e. without loops. If the array was an array of tuples I could just to

cells = matrix[array]

and get what I want, but the array is not in that format, and I couldn't find an efficient way to convert it to the desired form...

2
  • matrix[xy[:,0],xy[:,1]]? Commented Jan 6, 2017 at 10:09
  • or matrix[tuple(xy.T)] Not sure which is more efficient Commented Jan 6, 2017 at 10:47

1 Answer 1

1

You can make your array into a tuple of arrays like this:

tuple(array.T)

This matches the output style of np.where(), which can be indexed.

cells=matrix[tuple(array.T)]

you can also do standard numpy array slicing and get Divakar's answer in the comments:

cells=matrix[array[:,0],array[:,1]]

Sign up to request clarification or add additional context in comments.

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.