0
0
NumPydata~20 mins

np.newaxis for adding dimensions in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
np.newaxis Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of adding a new axis to a 1D array
What is the shape of the array b after adding a new axis using np.newaxis?
NumPy
import numpy as np

a = np.array([1, 2, 3])
b = a[:, np.newaxis]
print(b.shape)
A(3,)
B(3, 1)
C(1, 3)
D(1,)
Attempts:
2 left
💡 Hint
Think about how adding a new axis in the second position changes the shape.
data_output
intermediate
2:00remaining
Resulting array after adding new axis
What is the output of the array b after adding a new axis?
NumPy
import numpy as np

a = np.array([4, 5, 6])
b = a[np.newaxis, :]
print(b)
A[[4 5 6]]
B
[4
 5
 6]
C
[[4]
 [5]
 [6]]
D[4 5 6]
Attempts:
2 left
💡 Hint
Adding np.newaxis at the start adds a new row dimension.
visualization
advanced
2:30remaining
Visualizing shape changes with np.newaxis
Which option correctly describes the shape change when adding np.newaxis to a 2D array arr of shape (2, 3) as arr[:, :, np.newaxis]?
NumPy
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
new_arr = arr[:, :, np.newaxis]
print(new_arr.shape)
A(2, 3) - shape unchanged
B(2, 1, 3) - adds a new second dimension
C(1, 2, 3) - adds a new first dimension
D(2, 3, 1) - adds a new third dimension
Attempts:
2 left
💡 Hint
Adding np.newaxis at the end adds a new dimension at the last position.
🔧 Debug
advanced
2:00remaining
Identify the error when using np.newaxis incorrectly
What error will this code raise?
NumPy
import numpy as np

a = np.array([1, 2, 3])
b = a[np.newaxis, np.newaxis]
print(b.shape)
ASyntaxError: invalid syntax
BTypeError: unhashable type: 'slice'
C(1, 1, 3) - no error, shape is correct
DIndexError: too many indices for array
Attempts:
2 left
💡 Hint
Check how many dimensions the original array has and how many indices are used.
🚀 Application
expert
3:00remaining
Using np.newaxis to prepare data for broadcasting
Given two arrays a with shape (5,) and b with shape (3,), which option correctly uses np.newaxis to add dimensions so that a + b broadcasts to shape (5, 3)?
NumPy
import numpy as np

a = np.arange(5)
b = np.arange(3)

# Which option below correctly reshapes a and b for broadcasting?
Aa[:, np.newaxis] + b[np.newaxis, :]
Ba[np.newaxis, :] + b[:, np.newaxis]
Ca[:, np.newaxis] + b[:, np.newaxis]
Da[np.newaxis, :] + b[np.newaxis, :]
Attempts:
2 left
💡 Hint
Broadcasting works when dimensions are compatible or equal to 1.