Bird
0
0

Given a 2D NumPy array arr with shape (7, 1), which of the following code snippets correctly converts it to a 1D array without changing the order of elements?

hard📝 Application Q8 of 15
NumPy - Array Manipulation
Given a 2D NumPy array arr with shape (7, 1), which of the following code snippets correctly converts it to a 1D array without changing the order of elements?
Aarr = np.expand_dims(arr, axis=0)
Barr = np.squeeze(arr)
Carr = arr.reshape((1, 7))
Darr = arr.flatten()
Step-by-Step Solution
Solution:
  1. Step 1: Understand the shape

    Original shape is (7, 1), a 2D array with one singleton dimension.
  2. Step 2: Using np.squeeze()

    Removes singleton dimensions, converting shape to (7,), a 1D array.
  3. Step 3: Other options

    expand_dims adds dimensions, reshape changes shape but not to 1D, flatten returns a copy but also works.
  4. Step 4: Best option

    np.squeeze is the most direct and efficient method to convert (7,1) to (7,).
  5. Final Answer:

    arr = np.squeeze(arr) -> Option B
  6. Quick Check:

    Squeeze removes singleton dims without changing order [OK]
Quick Trick: Use squeeze to remove singleton dimensions efficiently [OK]
Common Mistakes:
  • Using reshape incorrectly and changing data layout
  • Using expand_dims which adds dimensions
  • Assuming flatten is the only way to get 1D

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes