Bird
0
0

Which code correctly does this using np.newaxis?

hard📝 Application Q15 of 15
NumPy - Array Manipulation
You have a 2D numpy array data with shape (100, 50). You want to add a new dimension at the front to represent batch size 1, making the shape (1, 100, 50). Which code correctly does this using np.newaxis?
Adata[np.newaxis:]
Bdata[np.newaxis, :, :]
Cdata[:, :, np.newaxis]
Ddata[:, np.newaxis, :]
Step-by-Step Solution
Solution:
  1. Step 1: Understand the original shape and desired shape

    Original shape is (100, 50). We want to add a new axis at the front to get (1, 100, 50).
  2. Step 2: Use np.newaxis at the front index

    Using data[np.newaxis, :, :] adds a new axis at position 0, resulting in shape (1, 100, 50).
  3. Step 3: Check other options

    data[np.newaxis:] does not add a new dimension (acts as slice data[:], shape (100,50)). data[:, np.newaxis, :] adds axis in middle (100, 1, 50), data[:, :, np.newaxis] adds axis at end (100, 50, 1).
  4. Final Answer:

    data[np.newaxis, :, :] -> Option B
  5. Quick Check:

    New axis front = data[np.newaxis, :, :] [OK]
Quick Trick: Add np.newaxis at front index for batch dimension [OK]
Common Mistakes:
  • Adding newaxis in wrong position
  • Using fewer indices than array dimensions
  • Confusing axis order for shape

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes