重新排列numpy 2D数组的列

时间:2013-11-28 11:39:45

标签: python arrays numpy edit-in-place

有没有办法将numpy 2D数组中列的顺序更改为新的任意顺序? 例如,我有一个数组

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
列上的

。因此,在新矩阵中,我希望原始的第一列保持原位,第二列移动到最后一列,依此类推。

是否有一个numpy功能呢?我有一个相当大的矩阵,并期望得到更大的矩阵,所以我需要一个解决方案,如果可能的话,快速和就地做到这一点(置换矩阵是不行的)

谢谢。

4 个答案:

答案 0 :(得分:62)

使用花式索引可以实现这一点:

>>> 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数组如何跨越内存,因此无法进行就地置换。

答案 1 :(得分:3)

通过将置换矩阵后乘以原始矩阵,我得到了基于矩阵的解决方案。这会改变元素在原始矩阵中的位置

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)

答案 2 :(得分:1)

我认为最简单的方法是:

launch.json

结果是:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "externalTerminal"
        }
    ]
}
'''

答案 3 :(得分:0)

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

a = np.random.permutation(a.T).T
相关问题