How to transpose a matrix (swap rows and columns) in Python

4 Answers

0 votes
def transpose_matrix(matrix):
    rows = len(matrix)
    cols = len(matrix[0])

    # create empty transpose matrix
    transpose = [[0 for _ in range(rows)] for _ in range(cols)]

    # fill transpose
    for i in range(rows):        # rows
        for j in range(cols):    # columns
            transpose[j][i] = matrix[i][j]

    return transpose


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

# call function
result = transpose_matrix(matrix)

# print result
for row in result:
    for val in row:
        print('{:5}'.format(val), end="")
    print()



'''
run:

    1    3    5
    2    4    6

'''

 



answered Jun 1, 2017 by avibootz
edited 1 day ago by avibootz
0 votes
matrix = [
    [1, 2],
    [3, 4],
    [5, 6]
]

transpose = [list(row) for row in zip(*matrix)]
print(transpose)



'''
run:

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

'''

 



answered 1 day ago by avibootz
0 votes
import numpy as np

matrix = np.array([
    [1, 2],
    [3, 4],
    [5, 6]
])

transpose = matrix.T
print(transpose)



'''
run:

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

'''

 



answered 1 day ago by avibootz
0 votes
matrix = [
    [1, 2],
    [3, 4],
    [5, 6]
]

z_matrix = zip(*matrix)
 
for row in z_matrix:
    print(list(row))
 
 

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

 



answered 1 day ago by avibootz
...