Rearrange columns of numpy 2D array

我只是一个虾纸丫 提交于 2019-11-27 18:57:48

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]])

Note that this is a copy, not a view. An in-place permutation is not possible in the general case, due to how numpy arrays are strided in memory.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!