0
0
NumPydata~10 mins

np.newaxis for adding dimensions in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add a new axis to the 1D array to make it 2D.

NumPy
import numpy as np
arr = np.array([1, 2, 3])
new_arr = arr[1]
print(new_arr.shape)
Drag options to blanks, or click blank then click option'
A[np.newaxis, np.newaxis]
B[np.newaxis, :]
C[np.newaxis]
D[:, np.newaxis]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [np.newaxis] alone does not add a new axis correctly.
Adding np.newaxis in the wrong position changes the shape differently.
2fill in blank
medium

Complete the code to add a new axis at the start of the array shape.

NumPy
import numpy as np
arr = np.array([4, 5, 6])
new_arr = arr[1]
print(new_arr.shape)
Drag options to blanks, or click blank then click option'
A[np.newaxis, :]
B[:, np.newaxis]
C[np.newaxis]
D[np.newaxis, np.newaxis]
Attempts:
3 left
💡 Hint
Common Mistakes
Placing np.newaxis after the colon adds the axis at the end, not the start.
Using just [np.newaxis] does not specify the position clearly.
3fill in blank
hard

Fix the error in the code to correctly add a new axis to the array.

NumPy
import numpy as np
arr = np.array([7, 8, 9])
new_arr = arr[1]
print(new_arr.shape)
Drag options to blanks, or click blank then click option'
A[np.newaxis]
B[np.newaxis, :]
C[:, np.newaxis]
Dnp.newaxis
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.newaxis without slicing causes errors.
Placing np.newaxis inside brackets incorrectly changes the shape.
4fill in blank
hard

Fill both blanks to create a 3D array by adding two new axes to the 1D array.

NumPy
import numpy as np
arr = np.array([10, 20, 30])
new_arr = arr[1][2]
print(new_arr.shape)
Drag options to blanks, or click blank then click option'
A[np.newaxis]
B[:, np.newaxis]
C[np.newaxis, np.newaxis]
D[np.newaxis, :]
Attempts:
3 left
💡 Hint
Common Mistakes
Using combined axes like [np.newaxis, np.newaxis] once instead of chaining twice.
Mixing slicing and brackets incorrectly.
5fill in blank
hard

Fill all three blanks to create a 4D array with shape (1, 1, 1, 3) from a 1D array.

NumPy
import numpy as np
arr = np.array([100, 200, 300])
new_arr = arr[1][2][3]
print(new_arr.shape)
Drag options to blanks, or click blank then click option'
A[np.newaxis]
B[:, np.newaxis]
C[np.newaxis, :]
D[np.newaxis, np.newaxis]
Attempts:
3 left
💡 Hint
Common Mistakes
Adding axes in wrong order changes the shape.
Using combined axes incorrectly.