Bird
0
0

How can you correctly add a 1D NumPy array b to each column of a 2D array A using broadcasting?

easy📝 Syntax Q3 of 15
NumPy - Broadcasting
How can you correctly add a 1D NumPy array b to each column of a 2D array A using broadcasting?
AA + b[:, np.newaxis]
BA + b.T
CA + b[np.newaxis, :]
DA + b.reshape(-1)
Step-by-Step Solution
Solution:
  1. Step 1: Understand the shapes

    Assume A has shape (m, n) and b has shape (n,). To add b to each column, b must be broadcast along rows.
  2. Step 2: Reshape b for broadcasting

    Using b[np.newaxis, :] changes b shape to (1, n), which can broadcast across A's rows.
  3. Final Answer:

    A + b[np.newaxis, :] -> Option C
  4. Quick Check:

    Shapes (m, n) + (1, n) broadcast to (m, n) [OK]
Quick Trick: Add 1D array as row vector for column-wise addition [OK]
Common Mistakes:
  • Using b[:, np.newaxis] which changes shape to (n,1) causing mismatch
  • Trying to transpose b without reshaping
  • Using reshape(-1) which doesn't add new axis

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes