Skip to content

Instantly share code, notes, and snippets.

@tomerfiliba
Created September 11, 2012 13:20
Show Gist options
  • Save tomerfiliba/3698403 to your computer and use it in GitHub Desktop.
Save tomerfiliba/3698403 to your computer and use it in GitHub Desktop.
get the indexes of the top n elements in a numpy 2d-array
import numpy as np
import bottleneck as bn
def top_n_indexes(arr, n):
idx = bn.argpartsort(arr, arr.size-n, axis=None)[-n:]
width = arr.shape[1]
return [divmod(i, width) for i in idx]
np.random.seed(47)
arr = np.random.rand(50, 50)
idx = top_n_indexes(arr, 8)
idx.sort(key = lambda tup: tup[0])
print idx
# [(5, 45), (11, 8), (16, 14), (24, 40), (25, 35), (31, 7), (35, 6), (49, 43)]
@githubsagnik
Copy link

Functions partsort and argpartsort have been renamed to partition and argpartition to match NumPy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment