詳解numpy中argsort函數

當你不瞭解一個函數的時候,你可以採用兩種方式:一種輸入來了解函數

print(help(np.argsort))

要麼就是 直接 點進函數來看函數的源代碼,可能源代碼都是英文,不太好理解,沒有關係,我們可以看源代碼裏面的例子,如果你還是不懂的話,就可以直接百度查詢了,接下來直奔主題 numpy中 argsort函數的用法:

def 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
    `a` that index data along the given axis in sorted order.
      Parameters
    ----------
    a : array_like
        Array to sort.
    axis : int or None, optional
        Axis along which to sort.  The default is -1 (the last axis). If None,
        the flattened array is used.

 參數就是傳入一個 numpy數組,axis來控制在哪個維度排序,返回的就是一個 numpy數組值從小到大的索引值

總結就一句話: argsort函數返回的是數組值從小到大的索引值

具體實例

One dimensional array:

    >>> x = np.array([3, 1, 2])
    >>> np.argsort(x)  #將 3,1,2 的索引值 按照 3,1,2的大小進行排序
    array([1, 2, 0])  

    Two-dimensional array:

    >>> x = np.array([[0, 3], [2, 2]])
    >>> x
    array([[0, 3],
           [2, 2]])

    >>> np.argsort(x, axis=0)  # sorts along first axis (down) 按列排序
    array([[0, 1],
           [1, 0]])

    >>> np.argsort(x, axis=1)  # sorts along last axis (across) # 按行排序
    array([[0, 1],
           [0, 1]])

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章