Sort using argsort in python

2020-07-20 04:03发布

问题:

I try to sort an array:

import numpy as np

arr = [5,3,7,2,6,34,46,344,545,32,5,22]
print "unsorted"
print arr

np.argsort(arr)

print "sorted"
print arr

But the output is:

unsorted
[5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]
sorted
[5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]

The array does not change at all

回答1:

There are two issues here; one is that np.argsort returns an array of the indices which would sort the original array, the second is that it doesn't modify the original array, just gives you another. This interactive session should help explain:

In [59]: arr = [5,3,7,2,6,34,46,344,545,32,5,22]

In [60]: np.argsort(arr)
Out[60]: array([ 3,  1,  0, 10,  4,  2, 11,  9,  5,  6,  7,  8])

Above, the [3, 1, 0, ...] means that item 3 in your original list should come first (the 2), then item 2 should come (the 3), then the first (index is 0, item is 5) and so on. Note that arr is still unaffected:

In [61]: arr
Out[61]: [5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]

You might not need this array of indices, and would find it easier to just use np.sort:

In [62]: np.sort(arr)
Out[62]: array([  2,   3,   5,   5,   6,   7,  22,  32,  34,  46, 344, 545])

But this still leaves arr alone:

In [68]: arr
Out[68]: [5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]

If you want to do it in place (modify the original), use:

In [69]: arr.sort()

In [70]: arr
Out[70]: [2, 3, 5, 5, 6, 7, 22, 32, 34, 46, 344, 545]


回答2:

np.argsort doesn't sort the list in place, it returns a list full of indicies that you are able to use to sort the list.

You must assign this returned list to a value:

new_arr = np.argsort(arr)

Then, to sort the list with such indices, you can do:

np.array(arr)[new_arr]


回答3:

Try

order = np.argsort(arr)
print np.array(arr)[order]

the argsort response is the index of the elements.



回答4:

If you want your array sorted in-place you want arr.sort():

In [1]: import numpy as np  
In [2]: arr = [5,3,7,2,6,34,46,344,545,32,5,22]

In [4]: print arr
[5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]

In [5]: arr.sort()
In [7]: print arr
[2, 3, 5, 5, 6, 7, 22, 32, 34, 46, 344, 545]