Bird
0
0

You want to normalize each column of a 2D numpy array by subtracting the column mean. Given arr shape (5,4), which code correctly uses broadcasting?

hard📝 Application Q9 of 15
NumPy - Broadcasting
You want to normalize each column of a 2D numpy array by subtracting the column mean. Given arr shape (5,4), which code correctly uses broadcasting?
Aarr - arr.mean(axis=0).reshape(5,1)
Barr - arr.mean(axis=1)
Carr - arr.mean(axis=1).reshape(1,4)
Darr - arr.mean(axis=0)
Step-by-Step Solution
Solution:
  1. Step 1: Calculate column means

    arr.mean(axis=0) returns shape (4,), the mean of each column.
  2. Step 2: Subtract column means from arr

    Subtracting (5,4) - (4,) broadcasts the means across rows, normalizing columns.
  3. Step 3: Check other options

    arr - arr.mean(axis=1) subtracts row means, incorrect. Options A and D reshape incorrectly causing errors.
  4. Final Answer:

    arr - arr.mean(axis=0) -> Option D
  5. Quick Check:

    Subtract column means with axis=0 mean [OK]
Quick Trick: Subtract axis=0 mean to normalize columns [OK]
Common Mistakes:
  • Using axis=1 for columns
  • Wrong reshape causing errors
  • Confusing row and column means

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes