Bird
0
0

You have a 3D array arr with shape (2, 3, 4). You want to compute the sum over the last two axes to get a 1D array. Which code achieves this?

hard📝 Application Q8 of 15
NumPy - Aggregation Functions
You have a 3D array arr with shape (2, 3, 4). You want to compute the sum over the last two axes to get a 1D array. Which code achieves this?
Anp.sum(arr, axis=(1, 2))
Bnp.sum(arr, axis=0)
Cnp.sum(arr, axis=2)
Dnp.sum(arr, axis=(0, 1))
Step-by-Step Solution
Solution:
  1. Step 1: Understand the array shape and axes

    Array shape is (2, 3, 4). Last two axes are 1 and 2.
  2. Step 2: Sum over axes 1 and 2

    Using axis=(1, 2) sums over the last two dimensions, resulting in shape (2,).
  3. Final Answer:

    np.sum(arr, axis=(1, 2)) produces the desired 1D array -> Option A
  4. Quick Check:

    Sum last two axes = axis=(1,2) [OK]
Quick Trick: Use tuple axis to sum multiple axes at once [OK]
Common Mistakes:
  • Summing only one axis instead of two
  • Using wrong axis numbers
  • Expecting 2D output instead of 1D

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes