Python 重新排列 numpy 二维数组的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20265229/
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
Rearrange columns of numpy 2D array
提问by 5xum
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
有没有办法将 numpy 2D 数组中列的顺序更改为新的任意顺序?例如,我有一个数组
array([[10, 20, 30, 40, 50],
[ 6, 7, 8, 9, 10]])
and I want to change it into, say
我想把它改成,说
array([[10, 30, 50, 40, 20],
[ 6, 8, 10, 9, 7]])
by applying the permutation
通过应用置换
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.
在列上。因此,在新矩阵中,我希望原始矩阵的第一列保持原位,第二列移动到最后一列,依此类推。
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)
是否有一个 numpy 函数来做到这一点?我有一个相当大的矩阵,并希望得到更大的矩阵,所以我需要一个解决方案,如果可能的话,它可以快速且适当地执行此操作(置换矩阵是不可行的)
Thank you.
谢谢你。
采纳答案by wim
This is possible in O(n)time and O(n)space using fancy indexing:
这在O(n)时间和O(n)空间中使用花式索引是可能的:
>>> import numpy as np
>>> a = np.array([[10, 20, 30, 40, 50],
... [ 6, 7, 8, 9, 10]])
>>> permutation = [0, 4, 1, 3, 2]
>>> idx = np.empty_like(permutation)
>>> idx[permutation] = np.arange(len(permutation))
>>> a[:, idx] # return a rearranged copy
array([[10, 30, 50, 40, 20],
[ 6, 8, 10, 9, 7]])
>>> a[:] = a[:, idx] # in-place modification of a
Note that a[:, idx]is returning a copy, not a view. An O(1)-space solution is not possible in the general case, due to how numpy arrays are strided in memory.
请注意,a[:, idx]在返回的副本,而不是一个视图。由于 numpy 数组在内存中是如何跨步的,因此在一般情况下不可能使用O(1)空间解决方案。
回答by Parth Paritosh
I have a matrix based solution for this, by post-multiplying a permutation matrix to the original one. This changes the position of the elements in original matrix
我有一个基于矩阵的解决方案,通过将置换矩阵后乘以原始矩阵。这会改变原始矩阵中元素的位置
import numpy as np
a = np.array([[10, 20, 30, 40, 50],
[ 6, 7, 8, 9, 10]])
# Create the permutation matrix by placing 1 at each row with the column to replace with
your_permutation = [0,4,1,3,2]
perm_mat = np.zeros((len(your_permutation), len(your_permutation)))
for idx, i in enumerate(your_permutation):
perm_mat[idx, i] = 1
print np.dot(a, perm_mat)

