Search code examples
pythonnumpymatrixswapfloating-accuracy

Python matrix swapping columns using numpy


This is my Y matrix I am trying to swap the columns (to make the columns [1,2,3,4,5] be in the place of [5,4,3,2,1]) But, this changes the numbers' accuracy

This is Y

> array([[ 0.0e+00,  1.0e-15,  0.0e+00,  0.0e+00,  0.0e+00],
>        [ 1.0e+00,  0.0e+00,  0.0e+00,  0.0e+00,  0.0e+00],
>        [-1.0e-02,  1.2e-02,  0.0e+00,  0.0e+00,  0.0e+00],
>        [ 1.0e-02, -1.0e-02,  1.0e+00,  0.0e+00,  0.0e+00]])

This the code

y1, y2= np.shape(Y)
 y2= y2-2
 for row in range (y1):
     for column in range (y2):
         Z[row, column]=Y[row, y2-column+1] 

This is Z

array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0.]])

How can I make it have the same accuracy?


Solution

  • Don't loop here, simply use np.flip

    x = np.array([[ 0.0e+00,  1.0e-15,  0.0e+00,  0.0e+00,  0.0e+00],
        [ 1.0e+00,  0.0e+00,  0.0e+00,  0.0e+00,  0.0e+00],
        [-1.0e-02,  1.2e-02,  0.0e+00,  0.0e+00,  0.0e+00],
        [ 1.0e-02, -1.0e-02,  1.0e+00,  0.0e+00,  0.0e+00]])
    
    np.flip(x, axis=1)
    
    array([[ 0.0e+00,  0.0e+00,  0.0e+00,  1.0e-15,  0.0e+00],
           [ 0.0e+00,  0.0e+00,  0.0e+00,  0.0e+00,  1.0e+00],
           [ 0.0e+00,  0.0e+00,  0.0e+00,  1.2e-02, -1.0e-02],
           [ 0.0e+00,  0.0e+00,  1.0e+00, -1.0e-02,  1.0e-02]])
    

    If you have a different order in mind, for example: 4, 3, 5, 2, 1, you can make use of advanced indexing:

    x[:, [3, 2, 4, 1, 0]]
    
    array([[ 0.0e+00,  0.0e+00,  0.0e+00,  1.0e-15,  0.0e+00],
       [ 0.0e+00,  0.0e+00,  0.0e+00,  0.0e+00,  1.0e+00],
       [ 0.0e+00,  0.0e+00,  0.0e+00,  1.2e-02, -1.0e-02],
       [ 0.0e+00,  1.0e+00,  0.0e+00, -1.0e-02,  1.0e-02]])