Home:ALL Converter>Extract elements from a 2d numpy array using a 2d array as indicies

Extract elements from a 2d numpy array using a 2d array as indicies

Ask Time:2018-06-08T21:57:30         Author:Francois

Json Formatter

jpp :

One way via NumPy array indexing.\n\nA = np.array([[1,2],[3,4]])\nidx = np.array([[0],[1]])\n\nres = A[np.arange(A.shape[0])[:, None], idx]\n\nprint(res)\n\n[[1]\n [4]]\n\n\nNote we need to ensure both row and column indexers have the same shape, in this case (n, 1), where n is the number of rows.",
2018-06-08T14:03:30
anishtain4 :

You can just slice the index first:\n\nin_array=np.arange(20).reshape(4,5)\nind=np.array([[0,2],[1,3]])\nin_array[ind[:,0],ind[:,1]]\narray([2, 8])\n\n\nAlso don't use the names such as input as they're built-in functions of python and you are overwriting them.",
2018-06-08T14:15:49
yy