Matrix Transpose in Python
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')]
Transpose Of Matrix in Python
You need to install numpy in order to import it
Numpy transpose returns similar result when
applied on 1D matrix
import numpy
mymatrix=[[1,2,3],[4,5,6]]
print(mymatrix)
print("\n")
print(numpy.transpose(mymatrix))
Basic matrix transpose in python
Your problem is two fold:
1- B was a label on matrix A, that is every modification to A, also modified B
2- B was local to the transpose function, and could not be accessed outside
A = [[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
def TS (A):
B = [row[:] for row in A] # make a copy of A, not assigning a new label on it.
for i in (range(len(A))):
for j in (range(len(A))):
B[i][j] = A[j][i]
return B
B = TS(A)
for i in range(len(A)):
for j in range(len(A)):
print(B[i][j], " ", end='')
print()
output:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Transpose only the matrix values with numpy if multiple of 3
You need to convert the mask M % 3 == 0
to indices. Something like this should work:
M = M.T
i, j = np.where(M % 3 == 0)
M[i, j] = (3 * j + i)**2
python matrix transpose and zip
question answers:
>>> import numpy as np
>>> first_answer = np.transpose(a)
>>> second_answer = [list(i) for i in zip(*a)]
thanks to afg for helping out
Transposing matrix twice using classes without numpy
You can create a new Matrix
object in transpose
and return that after printing its content.
For convenience I moved your printing code to a method for converting the matrix to a string (Note that a method called __repr__
will be implicit called by print).
Code:
from copy import deepcopy
class Matrix:
def __init__(self, rows):
self.rows = rows[:]
def transpose(self):
copy = deepcopy(self.rows)
transposed = [[copy[j][i] for j in range(len(copy))] for i in range(len(copy[0]))]
transposed_matrix = Matrix(transposed)
print(transposed_matrix)
return transposed_matrix
def __repr__(self):
matrix = ''
for element in self.rows:
for i in element:
matrix += '%2d' % ((i))
matrix += ' '
matrix = matrix[:-1]
matrix += '\n'
return matrix
Additional improvements:
- in
transpose
you can change the matrix transposition totransposed = list(map(list, zip(*self.rows)))
- use format string instead of
'%2d' % ((i))
->f'{i:2}'
join
is very helpful for formatting the matrix:return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)
Now the full code looks like this
class Matrix:
def __init__(self, rows):
self.rows = rows[:]
def transpose(self):
transposed = list(map(list, zip(*self.rows)))
transposed_matrix = Matrix(transposed)
print(transposed_matrix)
return transposed_matrix
def __repr__(self):
return '\n'.join(' '.join(f'{i:2}' for i in row) for row in self.rows)
python, matrix transpose with odd row reversed
Using no numpy
functions to reverse odd columns you could do something like:
import numpy as np
# just your input data
mat = np.arange(1.0, 13.0).reshape(3, 4).T
mat_no_numpy = np.zeros_like(mat)
rows, cols = mat.shape
for i in range(rows):
for j in range(cols):
if j % 2 == 0:
mat_no_numpy[i, j] = mat[i, j]
else:
# flip row-coordinate for odd columns
mat_no_numpy[i, j] = mat[rows - i - 1, j]
print(mat_no_numpy)
# [[ 1. 8. 9.]
# [ 2. 7. 10.]
# [ 3. 6. 11.]
# [ 4. 5. 12.]]
Alternatively, if numpy
functions are allowed, you can use a combination of slicing and np.flip
to flip every odd column:
import numpy as np
# just your input data
mat = np.arange(1.0, 13.0).reshape(3, 4).T
mat[:, 1::2] = np.flip(mat[:, 1::2])
print(mat)
# [[ 1. 8. 9.]
# [ 2. 7. 10.]
# [ 3. 6. 11.]
# [ 4. 5. 12.]]
Related Topics
C Function Called from Python Via Ctypes Returns Incorrect Value
What's the Difference Between Eval, Exec, and Compile
Using @Property Versus Getters and Setters
How to Find the Cumulative Sum of Numbers in a List
Find If 24 Hrs Have Passed Between Datetimes
What Is the Python Keyword "With" Used For
How to Input a Regex in String.Replace
Convert List of Dictionaries to a Pandas Dataframe
How to Measure Elapsed Time in Python
Combine Two Columns of Text in Pandas Dataframe
Saving Utf-8 Texts With Json.Dumps as Utf8, Not as \U Escape Sequence
How to Select a Variable by (String) Name