0
0
NumPydata~10 mins

np.newaxis for adding dimensions in NumPy - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - np.newaxis for adding dimensions
Start with 1D array
Use np.newaxis to add axis
Array shape changes
New dimension added
Result: Higher dimensional array
Start with a 1D array, apply np.newaxis to add a new dimension, resulting in a higher dimensional array.
Execution Sample
NumPy
import numpy as np
arr = np.array([1, 2, 3])
arr2d = arr[:, np.newaxis]
print(arr2d.shape)
print(arr2d)
This code adds a new axis to a 1D array to make it 2D with shape (3,1).
Execution Table
StepActionArray ShapeArray Content
1Create 1D array arr(3,)[1 2 3]
2Apply arr[:, np.newaxis](3, 1)[[1] [2] [3]]
3Print shape(3, 1)N/A
4Print array(3, 1)[[1] [2] [3]]
5EndN/AN/A
💡 Finished printing the new array with added dimension.
Variable Tracker
VariableStartAfter Step 2Final
arr[1 2 3][1 2 3][1 2 3]
arr2dN/A[[1] [2] [3]][[1] [2] [3]]
Key Moments - 2 Insights
Why does arr2d have shape (3, 1) instead of (1, 3)?
Because np.newaxis was used in the second dimension position (arr[:, np.newaxis]), it adds a new axis as a column, making shape (3,1). See execution_table step 2.
What happens if np.newaxis is used in the first dimension like arr[np.newaxis, :]?
It adds a new axis as the first dimension, changing shape to (1, 3). This is different from arr[:, np.newaxis].
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the shape of arr2d?
A(3,)
B(3, 1)
C(1, 3)
D(1,)
💡 Hint
Check the 'Array Shape' column at step 2 in execution_table.
At which step is the new axis added to the array?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look for the step where arr2d is created with shape (3, 1).
If we change arr2d = arr[np.newaxis, :], what would be the new shape?
A(3,)
B(3, 1)
C(1, 3)
D(1,)
💡 Hint
Recall that np.newaxis at the first dimension adds a new row dimension.
Concept Snapshot
np.newaxis adds a new dimension to numpy arrays.
Use it inside indexing like arr[:, np.newaxis] to add a column dimension.
This changes shape from (n,) to (n,1).
Use arr[np.newaxis, :] to add a row dimension, shape (1,n).
Useful for reshaping without copying data.
Full Transcript
We start with a 1D numpy array arr with shape (3,). Using np.newaxis inside indexing, like arr[:, np.newaxis], adds a new dimension. This changes the shape to (3, 1), turning the array into a 2D column vector. The variable arr2d holds this new array. Printing arr2d shows the new shape and content. This technique helps reshape arrays easily by adding dimensions where needed.