0
0
NumPydata~5 mins

Matrix transpose operations in NumPy

Choose your learning style9 modes available
Introduction

Transposing a matrix flips it over its diagonal. This changes rows into columns and columns into rows. It helps us rearrange data for analysis or math.

When you want to switch rows and columns in a dataset.
When preparing data for matrix multiplication.
When you need to align data shapes for algorithms.
When you want to rotate data orientation for visualization.
Syntax
NumPy
transposed_matrix = original_matrix.T

The .T attribute quickly transposes a NumPy array.

It works for 2D arrays (matrices) and higher dimensions.

Examples
Transpose a 2x2 matrix. Rows become columns.
NumPy
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
transposed = matrix.T
print(transposed)
Transpose a 2x3 matrix to 3x2.
NumPy
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.T)
Transpose a 3x2 matrix to 2x3.
NumPy
import numpy as np
matrix = np.array([[1, 2], [3, 4], [5, 6]])
transposed = matrix.T
print(transposed)
Sample Program

This program creates a 3x3 matrix and prints it. Then it prints the transposed matrix where rows and columns are swapped.

NumPy
import numpy as np

# Create a 3x3 matrix
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# Transpose the matrix
transposed_matrix = matrix.T

print("Original matrix:")
print(matrix)
print("\nTransposed matrix:")
print(transposed_matrix)
OutputSuccess
Important Notes

Transposing does not change the original matrix unless you assign the result back.

For 1D arrays, .T has no effect because they have no rows or columns.

You can also use np.transpose(matrix) which does the same thing.

Summary

Use .T to flip rows and columns of a matrix.

It helps prepare data for math and analysis.

Works easily with NumPy arrays.