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
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.
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).
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With