Numpy argsort - what is it doing?

后端 未结 9 2402
礼貌的吻别
礼貌的吻别 2020-11-28 19:15

Why is numpy giving this result:

x = numpy.array([1.48,1.41,0.0,0.1])
print x.argsort()

>[2 3 1 0]

when I\'d expect it to do this:

9条回答
  •  误落风尘
    2020-11-28 19:48

    numpy.argsort(a, axis=-1, kind='quicksort', order=None)

    Returns the indices that would sort an array

    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 that index data along the given axis in sorted order.

    Consider one example in python, having a list of values as

    listExample  = [0 , 2, 2456,  2000, 5000, 0, 1]
    

    Now we use argsort function:

    import numpy as np
    list(np.argsort(listExample))
    

    The output will be

    [0, 5, 6, 1, 3, 2, 4]
    

    This is the list of indices of values in listExample if you map these indices to the respective values then we will get the result as follows:

    [0, 0, 1, 2, 2000, 2456, 5000]
    

    (I find this function very useful in many places e.g. If you want to sort the list/array but don't want to use list.sort() function (i.e. without changing the order of actual values in the list) you can use this function.)

    For more details refer this link: https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.argsort.html

提交回复
热议问题