简体   繁体   English

重新排列 numpy 二维数组的列

[英]Rearrange columns of numpy 2D array

Is there a way to change the order of the columns in a numpy 2D array to a new and arbitrary order?有没有办法将 numpy 2D 数组中列的顺序更改为新的任意顺序? For example, I have an array例如,我有一个数组

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?是否有一个 numpy 函数来做到这一点? 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)我有一个相当大的矩阵,并希望得到更大的矩阵,所以我需要一个解决方案,如果可能的话,它可以快速且适当地执行此操作(置换矩阵是不可行的)

Thank you.谢谢。

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.请注意, a[:, idx]返回的是副本,而不是视图。 An O(1) -space solution is not possible in the general case, due to how numpy arrays are strided in memory.由于 numpy 数组在内存中是如何跨步的,因此在一般情况下不可能使用O(1)空间解决方案。

The easiest way in my opinion is:我认为最简单的方法是:

a = np.array([[10, 20, 30, 40, 50],
              [6,  7,  8,  9,  10]])
print(a[:, [0, 2, 4, 3, 1]])

the result is:结果是:

[[10 30 50 40 20]
 [6  8  10 9  7 ]]

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)

如果您正在寻找任何随机排列,如果您将列转置为行,排列行,然后转回,则可以在一行中完成:

a = np.random.permutation(a.T).T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM