Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Numpy.argsort() in basic python? [duplicate]

Tags:

python

numpy

is there a builtin function of Python that does on python.array what argsort() does on a numpy.array?

like image 784
Mermoz Avatar asked Aug 01 '10 14:08

Mermoz


People also ask

What is Argsort () in Python?

argsort() function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that would sort the array. Syntax : numpy.

What does NumPy Argsort return?

argsort. Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.

Is NumPy Argsort stable?

NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument.

What is the difference between Argsort and sort?

sort() returns the sorted array whereas np. argsort() returns an array of the corresponding indices. The figure shows how the algorithm transforms an unsorted array [10, 6, 8, 2, 5, 4, 9, 1] into a sorted array [1, 2, 4, 5, 6, 8, 9, 10] .


1 Answers

There is no built-in function, but it's easy to assemble one out of the terrific tools Python makes available:

def argsort(seq):     # http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python     return sorted(range(len(seq)), key=seq.__getitem__)  x = [5,2,1,10]  print(argsort(x)) # [2, 1, 0, 3] 

It works on Python array.arrays the same way:

import array x = array.array('d', [5, 2, 1, 10]) print(argsort(x)) # [2, 1, 0, 3] 
like image 154
unutbu Avatar answered Sep 25 '22 23:09

unutbu