Related to How to get indices of N maximum values in a numpy array?, I have a numpy matrix a
, and I would like to produce the array whose i-th row is the column indices of the top N elements of the i-th row of a
.
Following the top-voted answer to the linked question, adapting it for arrays, here is what I have so far (using N=4):
>>> a
array([[9, 4, 4, 3, 3, 9, 0, 4, 6, 0],
[3, 4, 6, 9, 5, 7, 1, 2, 8, 4]])
>>> ind=np.argpartition(a,-4)[:,-4:]
>>> ind
array([[1, 5, 8, 0],
[2, 3, 8, 5]])
>>> rows=np.transpose([np.arange(a.shape[0])])
>>> rows
array([[0],
[1]])
>>> ind_sorted = ind[rows,np.argsort(a[rows,ind])]
>>> ind_sorted
array([[1, 8, 5, 0],
[2, 5, 8, 3]])
This works, but seems to be not very (num)pythonic. I'm sure there's a better way to do the indexing that doesn't require a dummy array. Any suggestions?