Sort invariant for numpy.argsort with multiple dimensions

前端 未结 3 1403
谎友^
谎友^ 2020-11-30 11:50

numpy.argsort docs state

Returns:
index_array : ndarray, int Array of indices that sort a along the specified axis. If a is one-dimensional, <

3条回答
  •  青春惊慌失措
    2020-11-30 12:44

    This argsort produces a (3,2) array

    In [453]: idx=np.argsort(A,axis=-1)
    In [454]: idx
    Out[454]: 
    array([[0, 1],
           [1, 0],
           [0, 1]], dtype=int32)
    

    As you note applying this to A to get the equivalent of np.sort(A, axis=-1) isn't obvious. The iterative solution is sort each row (a 1d case) with:

    In [459]: np.array([x[i] for i,x in zip(idx,A)])
    Out[459]: 
    array([[-1.0856306 ,  0.99734545],
           [-1.50629471,  0.2829785 ],
           [-0.57860025,  1.65143654]])
    

    While probably not the fastest, it is probably the clearest solution, and a good starting point for conceptualizing a better solution.

    The tuple(inds) from the take solution is:

    (array([[0],
            [1],
            [2]]), 
     array([[0, 1],
            [1, 0],
            [0, 1]], dtype=int32))
    In [470]: A[_]
    Out[470]: 
    array([[-1.0856306 ,  0.99734545],
           [-1.50629471,  0.2829785 ],
           [-0.57860025,  1.65143654]])
    

    In other words:

    In [472]: A[np.arange(3)[:,None], idx]
    Out[472]: 
    array([[-1.0856306 ,  0.99734545],
           [-1.50629471,  0.2829785 ],
           [-0.57860025,  1.65143654]])
    

    The first part is what np.ix_ would construct, but it does not 'like' the 2d idx.


    Looks like I explored this topic a couple of years ago

    argsort for a multidimensional ndarray

    a[np.arange(np.shape(a)[0])[:,np.newaxis], np.argsort(a)]
    

    I tried to explain what is going on. The take function does the same sort of thing, but constructs the indexing tuple for a more general case (dimensions and axis). Generalizing to more dimensions, but still with axis=-1 should be easy.

    For the first axis, A[np.argsort(A,axis=0),np.arange(2)] works.

提交回复
热议问题