Data Science with Python Certification Data Science with Python NumPy Array Manipulation 3 — Questions and Answers
Question 1: When you index a NumPy array with another integer array (fancy indexing), does the result share memory with the original?
- Yes, it always returns a view
- No, it returns a copy (Correct answer)
- Only if the index array is sorted
- Only if both arrays have the same dtype
Correct answer: No, it returns a copy
Fancy (advanced) indexing always returns a copy, not a view, of the selected elements.
Question 2: What is the output of `np.zeros((3,3), dtype=int).diagonal()`?
- array([0, 0, 0]) (Correct answer)
- array([[0,0,0]])
- array([1, 1, 1])
- array([0])
Correct answer: array([0, 0, 0])
`diagonal()` extracts main-diagonal elements; a 3×3 zero matrix has three zeros on its diagonal.
Question 3: Which method returns a flattened copy of the array, always regardless of memory layout?
- array.ravel()
- array.flat
- array.flatten() (Correct answer)
- np.squeeze(array)
Correct answer: array.flatten()
`flatten()` always returns a new 1-D copy, while `ravel()` may return a view if possible.
Question 4: What does `np.roll(a, shift, axis)` do?
- Sorts array elements along the axis
- Rolls array elements along the given axis, wrapping around boundaries (Correct answer)
- Cumulatively sums along the axis
- Rotates the array's shape by 90 degrees
Correct answer: Rolls array elements along the given axis, wrapping around boundaries
`np.roll` circularly shifts elements along the specified axis, wrapping elements that go past the edge.
Question 5: What is the shape of `np.expand_dims(np.array([1,2,3]), axis=0)`?
- (3,)
- (1, 3) (Correct answer)
- (3, 1)
- (1, 1, 3)
Correct answer: (1, 3)
`expand_dims` with `axis=0` inserts a new axis at position 0, changing shape from (3,) to (1,3).
Question 6: How does `np.concatenate` differ from `np.stack`?
- concatenate joins along an existing axis; stack creates a new axis (Correct answer)
- stack joins along an existing axis; concatenate creates a new axis
- They are identical in behavior
- concatenate works only on 1-D arrays
Correct answer: concatenate joins along an existing axis; stack creates a new axis
`np.concatenate` joins arrays along an existing axis, while `np.stack` joins a sequence of arrays along a *new* axis.
Question 7: What does `np.where(condition, x, y)` return?
- Indices where condition is True
- Elements from x where condition is True, otherwise from y (Correct answer)
- A boolean mask of the condition
- The count of True values
Correct answer: Elements from x where condition is True, otherwise from y
With three arguments, `np.where` acts as an element-wise ternary: picks from x when True, from y when False.
When you index a NumPy array with another integer array (fancy indexing), does the result share memory with the original?