Data Science with Python Certification Data Science with Python NumPy Array Manipulation 2 — Questions and Answers
Question 1: What does `np.broadcast_to(a, shape)` do?
- Copies array data to match the new shape
- Returns a read-only view of the array broadcast to the given shape (Correct answer)
- Raises an error if shapes are incompatible
- Creates a writable array with the broadcast shape
Correct answer: Returns a read-only view of the array broadcast to the given shape
`np.broadcast_to` returns a read-only view of the array stretched to the target shape without copying data.
Question 2: Which function stacks 1-D arrays as rows into a 2-D array?
- np.hstack
- np.column_stack
- np.vstack (Correct answer)
- np.concatenate
Correct answer: np.vstack
`np.vstack` stacks arrays vertically (row-wise), converting 1-D arrays into rows of a 2-D array.
Question 3: What is the result of `np.arange(10).reshape(2,5)[1, ::2]`?
- array([5, 7, 9]) (Correct answer)
- array([6, 8])
- array([5, 6, 7, 8, 9])
- array([1, 3])
Correct answer: array([5, 7, 9])
Row index 1 gives [5,6,7,8,9], and step-2 slicing starting at 0 yields elements at positions 0,2,4 → [5,7,9].
Question 4: Which attribute gives the total number of elements in a NumPy array?
- array.shape
- array.ndim
- array.size (Correct answer)
- array.itemsize
Correct answer: array.size
`array.size` returns the total count of elements (product of all shape dimensions).
Question 5: What does `np.squeeze(a)` do?
- Flattens the array to 1-D
- Removes axes of length one from the array's shape (Correct answer)
- Compresses sparse values
- Normalizes values between 0 and 1
Correct answer: Removes axes of length one from the array's shape
`np.squeeze` removes dimensions of size 1, reducing unnecessary singleton axes from the shape.
Question 6: How do you swap axes 0 and 1 of a 2-D NumPy array `a`?
- np.flip(a)
- np.swapaxes(a, 0, 1) (Correct answer)
- np.moveaxis(a, 0, -1)
- a.reshape(a.shape[::-1])
Correct answer: np.swapaxes(a, 0, 1)
`np.swapaxes(a, 0, 1)` interchanges two specified axes, equivalent to a transpose for 2-D arrays.
Question 7: What does the `np.tile(a, reps)` function do?
- Reshapes `a` to the dimensions specified by `reps`
- Constructs an array by repeating `a` the number of times given by `reps` (Correct answer)
- Tiles `a` only along the last axis
- Broadcasts `a` to a shape given by `reps`
Correct answer: Constructs an array by repeating `a` the number of times given by `reps`
`np.tile` repeats the entire array `a` along each axis as specified by `reps`, constructing a larger array.
What does `np.broadcast_to(a, shape)` do?