How to rearrange array based upon index array

前端 未结 4 607
臣服心动
臣服心动 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条回答
  •  猫巷女王i
    2020-12-13 18:09

    You can simply use your "index" list directly, as, well, an index array:

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

    It tends to be much faster if idx is already an ndarray and not a list, even though it'll work either way:

    >>> %timeit arr[idx]
    100000 loops, best of 3: 2.11 µs per loop
    >>> ai = np.array(idx)
    >>> %timeit arr[ai]
    1000000 loops, best of 3: 296 ns per loop
    

提交回复
热议问题