问题描述
我正在寻找一种解决方案,可以帮助我完成以下任务.
I'm looking for a one line solution that would help me do the following.
假设我有
array = np.array([10, 20, 30, 40, 50])
我想根据输入顺序重新排列它.如果有一个名为arrange
的numpy函数,它将执行以下操作:
I'd like to rearrange it based upon an input ordering. If there were a numpy function called arrange
, it would do the following:
newarray = np.arrange(array, [1, 0, 3, 4, 2])
print newarray
[20, 10, 40, 50, 30]
通常,如果要重新排序的数组是m x n,而索引"数组是1 x n,则排序将由称为索引"的数组确定.
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".
numpy是否具有这样的功能?
Does numpy have a function like this?
推荐答案
您可以直接使用索引"列表以及索引数组:
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])
如果idx
已经是ndarray
而不是list
,则趋向于更快,即使它可以以任何一种方式工作:
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
这篇关于如何基于索引数组重新排列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!