Change language

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.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method