How to rearrange array based upon index array

前端 未结 4 606
臣服心动
臣服心动 2020-12-13 17:51

I\'m looking for a one line solution that would help me do the following.

Suppose I have

array = np.array([10, 20, 30, 40, 50])

I\

4条回答
  •  心在旅途
    2020-12-13 18:27

    For those who have the same confusion, I am actually looking for a slightly different version of "rearrange array based upon index". In my situation, the index array is indexing the target array instead of the source array. In other words, I am try to rearrange an array based on its position in the new array.

    In this case, simply apply an argsort before indexing. E.g.

    >>> arr = np.array([10, 20, 30, 40, 50])
    >>> idx = [1, 0, 3, 4, 2]
    >>> arr[np.argsort(idx)]
    array([20, 10, 50, 30, 40])
    

    Note the difference between this result and the desired result by op.

    One can verify back and forth

    >>> arr[np.argsort(idx)][idx] == arr
    array([ True,  True,  True,  True,  True])
    >>> arr[idx][np.argsort(idx)] == arr
    array([ True,  True,  True,  True,  True])
    

提交回复
热议问题