Rearrange columns of numpy 2D array

后端 未结 4 1460
庸人自扰
庸人自扰 2020-12-01 04:55

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


        
相关标签:
4条回答
  • 2020-12-01 05:24

    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 ]]
    
    0 讨论(0)
  • 2020-12-01 05:24

    If you're looking for any random permuation, you can do it in one line if you transpose columns into rows, permute the rows, then transpose back:

    a = np.random.permutation(a.T).T
    
    0 讨论(0)
  • 2020-12-01 05:39

    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)
    
    0 讨论(0)
  • 2020-12-01 05:40

    This is possible in O(n) time and O(n) space using fancy indexing:

    >>> 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.

    0 讨论(0)
提交回复
热议问题