如何根据索引数组重新排列数组 [英] How to rearrange array based upon index array

查看:54
本文介绍了如何根据索引数组重新排列数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种可以帮助我执行以下操作的单行解决方案.

假设我有

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,它往往会快得多,即使它可以以任何一种方式工作:

<预><代码>>>>%timeit arr[idx]100000 个循环,最好的 3 个:每个循环 2.11 µs>>>ai = np.array(idx)>>>%timeit arr[ai]1000000 个循环,最好的 3 个:每个循环 296 ns

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆