如何基于索引数组重新排列数组

编程入门 行业动态 更新时间:2024-10-07 12:26:57
本文介绍了如何基于索引数组重新排列数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一种解决方案,可以帮助我完成以下任务.

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

更多推荐

如何基于索引数组重新排列数组

本文发布于:2023-11-29 15:05:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646743.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   排列   索引

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!