Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort using argsort in python

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

like image 802
user2958912 Avatar asked Nov 06 '13 04:11

user2958912


2 Answers

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]
like image 66
TerryA Avatar answered Sep 24 '22 13:09

TerryA


Try

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

the argsort response is the index of the elements.

like image 43
Phil Cooper Avatar answered Sep 25 '22 13:09

Phil Cooper