Transpose matrix to one row in Python

m = [[ 1 , 2 ], [ 3 , 4 ], [ 5 , 6 ]]

for row in m:

print (row)

rez = [[m [j] [i] for j in range ( len (m))] for i in range ( len (m [ 0 ]))]

print ( "" )

for row in rez:

print (row)

Output:

 [1, 2] [3, 4] [5, 6] [1, 3, 5] [2, 4, 6] 

  1. Using zip: Zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each sequence of arguments or iterations. In this example, we are unboxing our array using * and then boxing it to get the transposition.

    matrix = [( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 ) , ( 10 , 11 , 12 )]

    for row in matrix:

    print (row)

    print ( "" )

    t_matrix = zip ( * matrix)

    for row in t_matrix:

      print ( row)

    Output:

     (1, 2, 3) (4, 5, 6) (7, 8, 9) (10, 11, 12) (1, 4, 7, 10) (2, 5, 8, 11) (3, 6, 9, 12)  

    Note: — If you want your result to be in the form [[1,4,7,10] [2,5,8,11] [3,6,9,12]], you can use t_matrix = map (list, zip -lightning (* matrix)).

  1. Using numpy: NumPy — is a versatile array processing package designed for efficient handling of large multidimensional arrays. The transpose method returns the transposed representation of the passed multidimensional matrix.

    # You need to install numpy in order to import it
    # Numpy transpose returns a similar result when
    # is applied to a 1D matrix

    import numpy 

    matrix = [[[ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]

    prin t (matrix)

    print ( "" )

    print (numpy.transpose (matrix))

This article is contributing to Mayank Rawat If you love Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or email the article [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.