We use transpose() to flip or swap the rows and columns of data. It helps us see data from a different angle.
0
0
transpose() for swapping axes in NumPy
Introduction
When you want to switch rows and columns in a table of numbers.
When preparing data for math operations that need a certain shape.
When you want to rotate or flip images stored as arrays.
When you want to change the order of dimensions in multi-dimensional data.
Syntax
NumPy
numpy.transpose(a, axes=None)a is the array you want to transpose.
axes is optional. It lets you choose how to reorder the dimensions.
Examples
Transpose a 2x2 matrix to swap rows and columns.
NumPy
import numpy as np arr = np.array([[1, 2], [3, 4]]) transposed = np.transpose(arr) print(transposed)
Transpose a 3D array by swapping the first two axes.
NumPy
import numpy as np arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) transposed = np.transpose(arr, axes=(1, 0, 2)) print(transposed)
Sample Program
This program creates a 2-row, 3-column array and then swaps rows and columns using transpose(). The output shows the original and transposed arrays.
NumPy
import numpy as np # Create a 2D array array_2d = np.array([[10, 20, 30], [40, 50, 60]]) print("Original array:") print(array_2d) # Transpose the array transposed_array = np.transpose(array_2d) print("\nTransposed array:") print(transposed_array)
OutputSuccess
Important Notes
For 2D arrays, transpose() swaps rows and columns.
For arrays with more dimensions, use the axes parameter to control how dimensions are reordered.
Transposing does not change the data, only how it is viewed or accessed.
Summary
transpose() flips or swaps the axes of an array.
It is useful to change the shape or orientation of data.
Use the axes parameter to customize the swap for multi-dimensional arrays.