Numpy argsort - what is it doing?

后端 未结 9 2354
礼貌的吻别
礼貌的吻别 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:39

    np.argsort returns the index of the sorted array given by the 'kind' (which specifies the type of sorting algorithm). However, when a list is used with np.argmax, it returns the index of the largest element in the list. While, np.sort, sorts the given array, list.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-28 19:50

    Just want to directly contrast the OP's original understanding against the actual implementation with code.

    numpy.argsort is defined such that for 1D arrays:

    x[x.argsort()] == numpy.sort(x) # this will be an array of True's
    

    The OP originally thought that it was defined such that for 1D arrays:

    x == numpy.sort(x)[x.argsort()] # this will not be True
    

    Note: This code doesn't work in the general case (only works for 1D), this answer is purely for illustration purposes.

    0 讨论(0)
提交回复
热议问题