0

I am trying to simply sort an array or a list using numpy.argsort(). For some reason, it is giving me results in random order:

import numpy

unsorted_list = [1.19021287, 1.19021287, 1.15190644, 1.12193492, 1.19021287, 1.25190644]
sorted_list = numpy.argsort(unsorted_list)
print sorted_list
array([3, 2, 0, 1, 4, 5])

It should return array([0, 1, 4, 3, 5, 4])

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
RKM
  • 3,151
  • 9
  • 37
  • 50
  • 2
    Why do you think 4 would show up in the result twice? – John La Rooy Jan 11 '16 at 02:37
  • The smallest value in your list is `1.12...`. It occurs at index 3, so the first value in the array returned by `argsort` is 3. The next smallest value is `1.15...`, at index 2, etc. "Randomness" (more accurately "behavior that is hard to predict") might occur with values that are equal. You can get more predictable behavior for those cases by using `kind='mergesort'`. – Warren Weckesser Jan 11 '16 at 06:11
  • 1
    I don't understand how you determined the array that it "should" return, but if what you are really trying to do is *rank* the values, see http://stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy – Warren Weckesser Jan 11 '16 at 06:19

1 Answers1

5

Well what does numpy.argsort do?

numpy.argsort(a, axis=-1, kind='quicksort', order=None)

Returns the indices that would sort an array.

Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

So it gave you the indices which would sort the array, from smallest values in the array to largest. For your given array these are:

[3, 2, 0, 1, 4, 5]

Corresponding to the values:

3 -> 1.12193492
2 -> 1.15190644
0 -> 1.19021287
1 -> 1.19021287
4 -> 1.19021287
5 -> 1.25190644

So, adding a trailing 0 for example, would result in the following indices returned:

[6 3 2 0 1 4 5]
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253