Permute rows and columns of a matrix

前端 未结 2 1414
我在风中等你
我在风中等你 2021-01-14 22:05

Assuming that I have the following matrix/array:

array([[0, 0, 1, 1, 1],
       [0, 0, 1, 0, 1],
       [1, 1, 0, 1, 1],
       [1, 0, 1, 0, 0],
       [1, 1         


        
2条回答
  •  独厮守ぢ
    2021-01-14 22:47

    You can perform the swap in a one-liner using integer array indexing:

    a = np.array([[0, 0, 1, 1, 1],
                  [0, 0, 1, 0, 1],
                  [1, 1, 0, 1, 1],
                  [1, 0, 1, 0, 0],
                  [1, 1, 1, 0, 0]])
    b = a.copy()
    
    # map 0 -> 4 and 1 -> 3 (N.B. Python indexing starts at 0 rather than 1)
    a[[4, 3, 0, 1]] = a[[0, 1, 4, 3]]
    
    print(repr(a))
    # array([[1, 1, 1, 0, 0],
    #        [1, 0, 1, 0, 0],
    #        [1, 1, 0, 1, 1],
    #        [0, 0, 1, 0, 1],
    #        [0, 0, 1, 1, 1]])
    

    Note that array indexing always returns a copy rather than a view - there's no way to swap arbitrary rows/columns of an array without generating a copy.


    In this particular case you could avoid the copy by using slice indexing, which returns a view rather than a copy:

    b = b[::-1] # invert the row order
    
    print(repr(b))
    # array([[1, 1, 1, 0, 0],
    #        [1, 0, 1, 0, 0],
    #        [1, 1, 0, 1, 1],
    #        [0, 0, 1, 0, 1],
    #        [0, 0, 1, 1, 1]])
    

    Update:

    You can use the same indexing approach to swap columns.

    c = np.arange(25).reshape(5, 5)
    print(repr(c))
    # array([[ 0,  1,  2,  3,  4],
    #        [ 5,  6,  7,  8,  9],
    #        [10, 11, 12, 13, 14],
    #        [15, 16, 17, 18, 19],
    #        [20, 21, 22, 23, 24]])
    
    c[[0, 4], :] = c[[4, 0], :]     # swap row 0 with row 4...
    c[:, [0, 4]] = c[:, [4, 0]]     # ...and column 0 with column 4
    
    print(repr(c))
    
    # array([[24, 21, 22, 23, 20],
    #        [ 9,  6,  7,  8,  5],
    #        [14, 11, 12, 13, 10],
    #        [19, 16, 17, 18, 15],
    #        [ 4,  1,  2,  3,  0]])
    

    I've used a different example array in this case - your version will yield an identical output after performing the row/column swaps which makes it difficult to understand what's going on.

提交回复
热议问题