is there a builtin function of Python that does on python.array
what argsort()
does on a numpy.array
?
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.
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.
NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument.
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] .
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.array
s the same way:
import array x = array.array('d', [5, 2, 1, 10]) print(argsort(x)) # [2, 1, 0, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With