Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix Transpose in Python

I am trying to create a matrix transpose function for python but I can't seem to make it work. Say I have

theArray = [['a','b','c'],['d','e','f'],['g','h','i']] 

and I want my function to come up with

newArray = [['a','d','g'],['b','e','h'],['c', 'f', 'i']] 

So in other words, if I were to print this 2D array as columns and rows I would like the rows to turn into columns and columns into rows.

I made this so far but it doesn't work

def matrixTranspose(anArray):     transposed = [None]*len(anArray[0])     for t in range(len(anArray)):         for tt in range(len(anArray[t])):             transposed[t] = [None]*len(anArray)             transposed[t][tt] = anArray[tt][t]     print transposed 
like image 661
Julio Diaz Avatar asked Feb 08 '11 19:02

Julio Diaz


People also ask

Is there a transpose function in Python?

transpose() function is one of the most important functions in matrix multiplication. This function permutes or reserves the dimension of the given array and returns the modified array. The numpy. transpose() function changes the row elements into column elements and the column elements into row elements.

How do you find the transpose of an array in Python?

NumPy Matrix transpose() – Transpose of an Array in Python The transpose of a matrix is obtained by moving the rows data to the column and columns data to the rows. If we have an array of shape (X, Y) then the transpose of the array will have the shape (Y, X).


1 Answers

Python 2:

>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']] >>> zip(*theArray) [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')] 

Python 3:

>>> [*zip(*theArray)] [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')] 
like image 165
jfs Avatar answered Oct 17 '22 08:10

jfs