Bird
0
0

Given a 2D NumPy array arr, you want to extract a subarray and modify it without changing the original. Which approach is correct?

hard📝 Application Q9 of 15
NumPy - Indexing and Slicing
Given a 2D NumPy array arr, you want to extract a subarray and modify it without changing the original. Which approach is correct?
sub_arr = arr[1:3, 0:2]
Asub_arr = arr[1:3][0:2]
Bsub_arr = arr[1:3, 0:2]
Csub_arr = arr[1:3, 0:2].copy()
Dsub_arr = arr.view()[1:3, 0:2]
Step-by-Step Solution
Solution:
  1. Step 1: Recognize slicing returns a view

    arr[1:3, 0:2] is a view sharing data with arr.
  2. Step 2: Use .copy() to avoid modifying original

    Calling .copy() creates an independent subarray.
  3. Final Answer:

    sub_arr = arr[1:3, 0:2].copy() -> Option C
  4. Quick Check:

    Use .copy() for independent 2D subarrays = A [OK]
Quick Trick: Always use .copy() for independent 2D slices [OK]
Common Mistakes:
  • Assuming slicing alone copies data
  • Using chained slicing incorrectly
  • Using .view() which still shares data

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes