Bird
0
0

Given a 2D NumPy array a with shape (5, 3) and a 1D array b = np.array([4, 5, 6]), which code correctly adds b to each row of a?

easy📝 Syntax Q3 of 15
NumPy - Broadcasting
Given a 2D NumPy array a with shape (5, 3) and a 1D array b = np.array([4, 5, 6]), which code correctly adds b to each row of a?
Aresult = a + b.T
Bresult = a + b.reshape(3, 1)
Cresult = a + b
Dresult = a + b.reshape(1, 5)
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes

    a has shape (5, 3), and b has shape (3,). Adding them directly triggers broadcasting along rows.
  2. Step 2: Understand broadcasting rules

    Since b matches the second dimension of a, it broadcasts across rows automatically.
  3. Step 3: Evaluate options

    result = a + b adds b directly, which is correct. result = a + b.reshape(3, 1) reshapes b incorrectly. result = a + b.T uses transpose on 1D array (no effect). result = a + b.reshape(1, 5) reshapes b to (1,5), incompatible with a.
  4. Final Answer:

    result = a + b -> Option C
  5. Quick Check:

    1D array shape matches columns; direct addition works. [OK]
Quick Trick: Add 1D array matching columns directly to 2D array. [OK]
Common Mistakes:
  • Reshaping 1D array incorrectly before addition.
  • Assuming transpose affects 1D arrays.
  • Mismatching dimensions causing errors.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes