-1

The first output is correct. But somehow argsort gives wrong output for the second array:

>>> np.argsort(np.array([ 0.62678927,  0.36816272,  0.31044763,  0.44873312,  0.3101446 ]))
array([4, 2, 1, 3, 0])

>>> np.argsort(np.array([ 0.36816272,  0.62678927,  0.13509969,  0.54590815,  0.13493432]))
array([4, 2, 0, 3, 1])

After spending 2 hours on it, I'm convinced that this problem is either too trivial or too technical. I'm using Anaconda virtual environments and have tested it with numpy 1.11.3 and 1.10.4

MediocreMyna
  • 269
  • 1
  • 5
  • 12
  • 1
    What is the issue exactly? The output is correct as 0.13493432 < 0.13509969 < 0.36816272 < 0.54590815 < 0.62678927. – fuglede Jan 12 '17 at 21:10
  • but the result seems correct, what did you expect? – MSeifert Jan 12 '17 at 21:10
  • 1
    Thanks for your responses. But I was expecting the second command to return `[2, 4, 1, 3, 0]`. As 0.6 is the largest it should have a number `4` associated with it. What am I missing? – MediocreMyna Jan 12 '17 at 21:18
  • 1
    But that would be the indices after sorting the array but `argsort` returns the "_indices that would sort the array_" (Source: [argsort documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy-argsort)) – MSeifert Jan 12 '17 at 21:20
  • @MSeifert. Got it. I'm dumb. Thanks for pointing it out. – MediocreMyna Jan 12 '17 at 21:26
  • 1
    Note also that your expected result is exactly the inverse of the output of `np.argsort` as a permutation; that is, you could get your expected result through `s = np.argsort(a)`, `s_inv = np.empty(5)`, `s_inv[s] = np.arange(5)`. It is thus rather unfortunate that in your first case, `s[s]` happens to be `np.arange(5)`. – fuglede Jan 12 '17 at 21:34

1 Answers1

2

It looks like you're under the impression that np.argsort(x) returns an array such that np.argsort(x)[i] is where x[i] goes in sorted order. That's not how it works.

np.argsort(x) returns an array such that x[np.argsort(x)[i]] goes in position i in sorted order. This produces the effect that

x[np.argsort(x)]

is equivalent to

np.sort(x)

This happens to produce the same result as the behavior you expected for the first array, but not for the second.

user2357112
  • 260,549
  • 28
  • 431
  • 505