Python 如何根据索引数组重新排列数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26194389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to rearrange array based upon index array
提问by hlin117
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:
我想根据输入顺序重新排列它。如果有一个名为 的 numpy 函数arrange,它将执行以下操作:
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".
正式地,如果要重新排序的数组是 mxn,而“索引”数组是 1 xn,则排序将由称为“索引”的数组确定。
Does numpy have a function like this?
numpy 有这样的功能吗?
采纳答案by DSM
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 idxis already an ndarrayand not a list, even though it'll work either way:
如果idx已经是 anndarray而不是 a list,它往往会快得多,即使它可以以任何一种方式工作:
>>> %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
回答by Jiaming Huang
for those whose index is 2d array, you can use map function. Here is an example:
对于那些索引为二维数组的人,您可以使用 map 函数。下面是一个例子:
a = np.random.randn(3, 3)
print(a)
print(np.argsort(a))
print(np.array(list(map(lambda x, y: y[x], np.argsort(a), a))))
the output is
输出是
[[-1.42167035 0.62520498 2.02054623]
[-0.17966393 -0.01561566 0.24480554]
[ 1.10568543 0.00298402 -0.71397599]]
[[0 1 2]
[0 1 2]
[2 1 0]]
[[-1.42167035 0.62520498 2.02054623]
[-0.17966393 -0.01561566 0.24480554]
[-0.71397599 0.00298402 1.10568543]]
回答by Pau B
If you want to sort it but descending:
如果你想排序但降序:
a = np.array([1,2,3,4,5])
np.argsort(a)
> array([0, 1, 2, 3, 4])
np.argsort(-a)
> array([4, 3, 2, 1, 0])

