Numpy:基于索引数组重新排列数组

时间:2023-02-08 15:42:18

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'd like to rearrange it based upon an input ordering. If there were a numpy function called arrange, it would do the following:

我想根据输入顺序重新排列它。如果有一个名为arrange的numpy函数,它将执行以下操作:

newarray = np.arrange(array, [1, 0, 3, 4, 2])
print newarray

    [20, 10, 40, 50, 30]

Formally, if the array to be reordered is m x n, and the "index" array is 1 x n, the ordering would be determined by the array called "index".

形式上,如果要重新排序的数组是m x n,并且“index”数组是1 x n,则排序将由名为“index”的数组确定。

Does numpy have a function like this?

numpy有这样的功能吗?

1 个解决方案

#1


28  

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:

如果idx已经是ndarray而不是列表,它往往会快得多,即使它可以以任何方式工作:

>>> %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

#1


28  

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:

如果idx已经是ndarray而不是列表,它往往会快得多,即使它可以以任何方式工作:

>>> %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