python - Can numpy argsort handle ties? -


this question has answer here:

i have numpy array:

foo = array([3, 1, 4, 0, 1, 0]) 

i want top 3 items. calling

foo.argsort()[::-1][:3] 

returns

array([2, 0, 4]) 

notice values foo[1] , foo[4] equal, numpy.argsort() handles tie returning index of item appears last in array; i.e. index 4.

for application can't have tie breaking bias end of array, how can implement random tie break? is, half time array([2, 0, 4]), , other half array([2, 0, 1]).

here's 1 approach:

use numpy.unique both sort array , remove duplicate items. pass return_inverse argument indices sorted array give values of original array. then, can of indices of tied items finding indices of inverse array values equal index unique array item.

for example:

foo = array([3, 1, 4, 0, 1, 0]) foo_unique, foo_inverse = unique(foo, return_inverse=true)  # put largest items first foo_unique = foo_unique[::-1] foo_inverse = -foo_inverse + len(foo_unique) - 1  foo_top3 = foo_unique[:3]  # indices foo of top item first_indices = (foo_inverse == 0).nonzero()  # choose 1 @ random first_random_idx = random.choice(first_indices)  second_indices = (foo_inverse == 1).nonzero() second_random_idx = random.choice(second_indices)  # , on... 

numpy.unique implemented using argsort, glance @ implementation might suggest simpler approach.


Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -