Have numpy argsort return an array of 2d indices?

前端 未结 2 1526
天命终不由人
天命终不由人 2020-12-30 03:18

If we have a 1d array

arr = np.random.randint(7, size=(5))
# [3 1 4 6 2]
print np.argsort(arr)
# [1 4 0 2 3] <= The indices in the sorted order    
         


        
2条回答
  •  难免孤独
    2020-12-30 03:57

    From the documentation on numpy.argsort:

    ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
    

    Indices of the sorted elements of a N-dimensional array.

    An example:

    >>> x = np.array([[0, 3], [2, 2]])
    >>> x
    array([[0, 3],
           [2, 2]])
    >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
    >>> ind # a tuple of arrays containing the indexes
    (array([0, 1, 1, 0]), array([0, 0, 1, 1]))
    >>> x[ind]  # same as np.sort(x, axis=None)
    array([0, 2, 2, 3])enter code here
    

提交回复
热议问题