Have numpy argsort return an array of 2d indices?

前端 未结 2 1524
天命终不由人
天命终不由人 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:46

    Apply numpy.argsort on flattened array and then unravel the indices back to (3, 3) shape:

    >>> arr = np.array([[5, 2, 4],
    [3, 3, 3],
    [6, 1, 2]])
    >>> np.dstack(np.unravel_index(np.argsort(arr.ravel()), (3, 3)))
    array([[[2, 1],
            [0, 1],
            [2, 2],
            [1, 0],
            [1, 1],
            [1, 2],
            [0, 2],
            [0, 0],
            [2, 0]]])
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题