Created
September 11, 2012 13:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Functions partsort and argpartsort have been renamed to partition and argpartition to match NumPy.