如何根据索引数组重新排列数组 [英] How to rearrange array based upon index array
问题描述
我正在寻找一种可以帮助我执行以下操作的单行解决方案.
假设我有
array = np.array([10, 20, 30, 40, 50])
我想根据输入顺序重新排列它.如果有一个名为 arrange
的 numpy 函数,它将执行以下操作:
newarray = np.arrange(array, [1, 0, 3, 4, 2])打印新数组[20, 10, 40, 50, 30]
形式上,如果要重新排序的数组是 m x n,而索引"数组是 1 x n,则排序将由名为索引"的数组确定.
numpy 有这样的功能吗?
你可以直接使用你的索引"列表,就像一个索引数组:
<预><代码>>>>arr = np.array([10, 20, 30, 40, 50])>>>idx = [1, 0, 3, 4, 2]>>>arr[idx]数组([20, 10, 40, 50, 30])如果 idx
已经是 ndarray
而不是 list
,它往往会快得多,即使它可以以任何一种方式工作:
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:
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".
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])
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
这篇关于如何根据索引数组重新排列数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!