Reputation: 39
I am trying to extract elements from a 2 dimensional array, a
, and I am using a 2 dimensional array of indices, b
, representing x/y coordinates. I have found something similar for a 1D array but I was unable to successfully apply it to a 2D array: Python - How to extract elements from an array based on an array of indices?
a = np.random.randn(10,7)
a = a.astype(int)
b = np.array([[1, 2], [2,3], [3,5], [2,7], [5,6]])
I have been using the bit of code below, however it returns a 3D matrix with values from the rows of each of the indices:
result2 = np.array(a)[b]
result2
Out[101]:
array([[[ 0, -1, 0, 0, 0, 1, 0],
[ 0, -1, 0, 0, 0, 0, 0]],
[[ 0, -1, 0, 0, 0, 0, 0],
[-1, 0, 0, 1, 0, 0, 0]],
[[-1, 0, 0, 1, 0, 0, 0],
[ 0, 0, -1, -2, 1, 0, 0]],
[[ 0, -1, 0, 0, 0, 0, 0],
[-1, 0, 0, 0, 0, 0, 1]],
[[ 0, 0, -1, -2, 1, 0, 0],
[ 1, 0, 0, 1, 0, -1, 0]]])
How can I modify b
in order to index (column 1,row 2) ... (column 2, row 3)... (column 3, row 5) ... etc?
...
This is a minimal reproducible example and my actual data involves me indexing 500 cells in a 100x100 matrix (using an array of x/y coordinates/indices, size (500x2), similar to the above b
). Would it be best to use a for loop in this case? Something along the lines of ...
for i in b:
for j in b:
result2 = np.array(a)[i,j]
Upvotes: 1
Views: 3352
Reputation: 1207
I've encountered the same issue not long ago, and the answer is actually quite simple :
result = a[b[:,0], b[:,1]]
Upvotes: 1