python - How to sort a list based on the output of numpy's argsort function -
i have list this:
mylist = [10,30,40,20,50]
now use numpy's argsort
function indices sorted list:
import numpy np = np.argsort(mylist)
which gives me output:
array([0, 3, 1, 2, 4])
when want sort array using so
works fine:
myarray = np.array([1,2,3,4,5]) myarray[so] array([1, 4, 2, 3, 5])
but when apply list, not work throws error
mylist2 = [1,2,3,4,5] mylist2[so]
typeerror: integer arrays 1 element can converted index
how can use so
sort list without using for-loop , without converting list array first?
you can't. have convert array back.
mylistsorted = list(np.array(mylist)[so])
edit: ran benchmarks comparing numpy way list comprehension. numpy ~27x faster
>>> timeit import timeit >>> import numpy np >>> mylist = list(np.random.rand(100)) >>> = np.argsort(mylist) #converts list numpy internally >>> timeit(lambda: [mylist2[i] in so]) 12.29590070003178 >>> myarray = np.random.rand(100) >>> = np.argsort(mylist) >>> timeit(lambda: a[o]) 0.42915570305194706
Comments
Post a Comment