Bird
0
0

You have a 2D NumPy array representing a grid of values. How can you use fancy indexing with integer arrays to extract the diagonal elements?

hard📝 Application Q8 of 15
NumPy - Indexing and Slicing
You have a 2D NumPy array representing a grid of values. How can you use fancy indexing with integer arrays to extract the diagonal elements?
AUse arr[:, [0,1,2]] to select columns
BUse slicing like arr[0:3, 0:3]
CUse the same list for row and column indices, e.g., arr[[0,1,2], [0,1,2]]
DUse boolean indexing with True on diagonal
Step-by-Step Solution
Solution:
  1. Step 1: Understand diagonal extraction

    Diagonal elements have equal row and column indices.
  2. Step 2: Apply fancy indexing

    Using the same list for rows and columns selects diagonal elements.
  3. Final Answer:

    Use the same list for row and column indices, e.g., arr[[0,1,2], [0,1,2]] -> Option C
  4. Quick Check:

    Diagonal = arr[[i,i]] for i in indices [OK]
Quick Trick: Match row and column indices to get diagonal [OK]
Common Mistakes:
  • Using slicing selects submatrix, not diagonal
  • Confusing boolean indexing
  • Selecting columns only

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes