python - Indexing a multidimensional Numpy array with an array of indices -


let have numpy array a shape (10, 10, 4, 5, 3, 3), , 2 lists of indices, b , c, of shape (1000, 6) , (1000, 5) respectively, represent indices , partial indices array. want use indices access array, producing arrays of shape (1000,) , (1000, 3), respectively.

i know of few ways this, they're unwieldy , rather un-pythonic, example converting indices tuples or indexing each axis separately.

a = np.random.random((10, 10, 4, 5, 3, 3)) b = np.random.randint(3, size=(1000, 6)) c = np.random.randint(3, size=(1000, 5))  # method 1  tuple_index_b = [tuple(row) row in b] tuple_index_c = [tuple(row) row in c]  output_b = np.array([a[row] row in tuple_index_b]) output_c = np.array([a[row] row in tuple_index_c])  # method 2  output_b = a[b[:, 0], b[:, 1], b[:, 2], b[:, 3], b[:, 4], b[:, 5]] output_c = a[c[:, 0], c[:, 1], c[:, 2], c[:, 3], c[:, 4]] 

obviously, neither of these methods elegant or easy extend higher dimensions. first slow, 2 list comprehensions, , second requires write out each axis separately. intuitive syntax, a[b] returns array of shape (1000, 6, 10, 4, 5, 3, 3) reason, related broadcasting.

so, there way in numpy doesn't involve manual labor/time?

edit: not duplicate, since question deals list of multidimensional indices, , not single index, , has produced useful new methods.

you can convert index tuple each column separate element , use __getitem__, assuming indices first few dimensions:

a.__getitem__(tuple(b.t)) 

or simply:

a[tuple(b.t)] 

(a.__getitem__(tuple(b.t)) == output_b).all() # true  (a.__getitem__(tuple(c.t)) == output_c).all() # true  (a[tuple(b.t)] == output_b).all() # true  (a[tuple(c.t)] == output_c).all() # true 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -