0
0
NumPydata~10 mins

transpose() for swapping axes in NumPy - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - transpose() for swapping axes
Start with array
Call transpose()
Swap axes
Return new array with swapped axes
The transpose() function takes an array and swaps its axes, returning a new array with dimensions flipped.
Execution Sample
NumPy
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
transposed = arr.transpose()
print(transposed)
This code creates a 2x3 array and swaps its axes to become 3x2.
Execution Table
StepActionArray ShapeArray Content
1Create original array(2, 3)[[1 2 3] [4 5 6]]
2Call transpose()(3, 2)[[1 4] [2 5] [3 6]]
3Print transposed array(3, 2)[[1 4] [2 5] [3 6]]
4End--
💡 transpose() swaps the axes from (2,3) to (3,2), then execution ends.
Variable Tracker
VariableStartAfter transpose()Final
arr[[1 2 3] [4 5 6]][[1 2 3] [4 5 6]][[1 2 3] [4 5 6]]
transposedN/A[[1 4] [2 5] [3 6]][[1 4] [2 5] [3 6]]
Key Moments - 2 Insights
Why does the shape change from (2, 3) to (3, 2) after transpose()?
Because transpose() swaps the rows and columns axes, so the first dimension becomes the second and vice versa, as shown in execution_table step 2.
Does transpose() modify the original array?
No, transpose() returns a new array with swapped axes; the original array remains unchanged, as seen in variable_tracker where 'arr' stays the same.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the shape of the transposed array?
A(6, 1)
B(3, 2)
C(2, 3)
D(1, 6)
💡 Hint
Refer to the 'Array Shape' column in execution_table row with Step 2.
At which step does the array content change to swapped axes?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Check the 'Array Content' column in execution_table for when the shape changes.
If we did not call transpose(), what would be the shape of 'transposed' variable?
A(3, 2)
B(2, 3)
CN/A (variable not defined)
D(1, 6)
💡 Hint
Look at variable_tracker for 'transposed' before transpose() is called.
Concept Snapshot
transpose() swaps the axes of an array.
Syntax: new_array = array.transpose()
Original array shape (m, n) becomes (n, m).
Original array is unchanged.
Useful for switching rows and columns.
Full Transcript
We start with a 2 by 3 array. When we call transpose(), it swaps the rows and columns, changing the shape to 3 by 2. The original array stays the same. The new array has the axes swapped, so rows become columns and columns become rows. This is useful when you want to flip the dimensions of your data.