重新排列numpy的二维数组的列 [英] Rearrange columns of numpy 2D array
问题描述
有没有办法在numpy的二维阵列,以改变列的顺序,以一种新的任意阶?
例如,我有一个数组
Is there a way to change the order of the columns in a numpy 2D array to a new and arbitrary order? For example, I have an array
array([[10, 20, 30, 40, 50],
[ 6, 7, 8, 9, 10]])
和我想把它变成,说
array([[10, 30, 50, 40, 20],
[ 6, 8, 10, 9, 7]])
通过将置换
0 -> 0
1 -> 4
2 -> 1
3 -> 3
4 -> 2
在列。在新的矩阵,因此,我希望原始的第一列保持就位,所述第二移动到最后一列等
on the columns. In the new matrix, I therefore want the first column of the original to stay in place, the second to move to the last column and so on.
有一个numpy的功能呢?我有一个相当大的矩阵,并期望得到更大的人,所以我需要一个解决方案,快速,到位做到这一点,如果可能的(置换矩阵是一个不走)
Is there a numpy function to do it? I have a fairly large matrix and expect to get even larger ones, so I need a solution that does this quickly and in place if possible (permutation matrices are a no-go)
感谢您。
推荐答案
这是可以使用索引看中的:
This is possible using fancy indexing:
>>> import numpy as np
>>> a = np.array([[10, 20, 30, 40, 50],
... [ 6, 7, 8, 9, 10]])
>>> your_permutation = [0,4,1,3,2]
>>> i = np.argsort(your_permutation)
>>> i
array([0, 2, 4, 3, 1])
>>> a[:,i]
array([[10, 30, 50, 40, 20],
[ 6, 8, 10, 9, 7]])
这篇关于重新排列numpy的二维数组的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!