How to Transpose Array in NumPy: Simple Guide
To transpose an array in NumPy, use the
.T attribute or the np.transpose() function. Both methods flip the array's axes, turning rows into columns and vice versa.Syntax
There are two common ways to transpose arrays in NumPy:
array.T: A simple attribute that returns the transposed array.np.transpose(array, axes=None): A function that returns a view of the array with axes permuted. Ifaxesis not given, it reverses the axes.
python
import numpy as np # Using .T attribute transposed_array = array.T # Using np.transpose function transposed_array_func = np.transpose(array, axes=None)
Example
This example shows how to transpose a 2D NumPy array using both .T and np.transpose(). The output demonstrates that rows become columns.
python
import numpy as np array = np.array([[1, 2, 3], [4, 5, 6]]) # Transpose using .T transposed = array.T # Transpose using np.transpose() transposed_func = np.transpose(array) print("Original array:\n", array) print("\nTransposed with .T:\n", transposed) print("\nTransposed with np.transpose():\n", transposed_func)
Output
Original array:
[[1 2 3]
[4 5 6]]
Transposed with .T:
[[1 4]
[2 5]
[3 6]]
Transposed with np.transpose():
[[1 4]
[2 5]
[3 6]]
Common Pitfalls
Common mistakes when transposing arrays include:
- Trying to transpose a 1D array, which has no effect because it has only one axis.
- Confusing
.Twith copying; transposing returns a view, not a copy. - Using
np.transpose()with incorrectaxesorder, which can lead to unexpected shapes.
python
import numpy as np # 1D array transpose has no effect arr_1d = np.array([1, 2, 3]) print("1D array transpose with .T:", arr_1d.T) # Using np.transpose with wrong axes arr_3d = np.arange(8).reshape(2,2,2) # Correct transpose (reverse axes) correct = np.transpose(arr_3d) # Wrong axes order (may cause confusion) wrong = np.transpose(arr_3d, axes=(1,0,2)) print("\nOriginal shape:", arr_3d.shape) print("Correct transpose shape:", correct.shape) print("Wrong transpose shape:", wrong.shape)
Output
1D array transpose with .T: [1 2 3]
Original shape: (2, 2, 2)
Correct transpose shape: (2, 2, 2)
Wrong transpose shape: (2, 2, 2)
Quick Reference
| Method | Description | Example |
|---|---|---|
.T | Simple attribute to transpose array axes | array.T |
np.transpose() | Function to permute axes, default reverses axes | np.transpose(array) |
np.transpose(array, axes=...) | Transpose with custom axes order | np.transpose(array, axes=(1,0)) |
Key Takeaways
Use
.T for quick transposing of 2D arrays in NumPy.Use
np.transpose() to transpose arrays with more than two dimensions or to specify axes order.Transposing a 1D array does not change it because it has only one axis.
Both
.T and np.transpose() return views, not copies, so changes affect the original array.Be careful with the
axes parameter in np.transpose() to avoid unexpected shapes.