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
Try
the argsort response is the index of the elements.
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:Above, the
[3, 1, 0, ...]
means that item3
in your original list should come first (the2
), then item2
should come (the3
), then the first (index is0
, item is5
) and so on. Note thatarr
is still unaffected:You might not need this array of indices, and would find it easier to just use
np.sort
:But this still leaves
arr
alone:If you want to do it in place (modify the original), use:
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:
Then, to sort the list with such indices, you can do:
If you want your array sorted in-place you want
arr.sort()
: