Write a NumPy function that subtracts each row's mean from a 2-D array and returns a new array of the same shape. It tests axis-wise reductions, the keepdims argument, and how broadcasting aligns a column of row means with the original matrix.
Write `center_rows(X)` that subtracts each row's mean from that row of a 2-D NumPy array `X`. Return an array of the same shape, with each row summing to approximately zero.
The function must:
- Reduce along `axis=1` with `keepdims=True` so the mean has shape `(n, 1)` and broadcasts against `X`.
- Not mutate the input.
Example:
```python
X = np.array([[1., 2., 3.],
[4., 6., 8.]])
center_rows(X)
# array([[-1., 0., 1.],
# [-2., 0., 2.]])
```
```hint Compare the shapes
Write the shape of the row means next to the shape of `X` and line them up from the right, the way NumPy's broadcasting rules do.
```
### What a Strong Answer Covers
- A row-wise reduction whose result has shape `(n, 1)`, and why that shape lines up with `X` under broadcasting
- Returning a new array while leaving the caller's input unchanged
- Inputs that are not already float arrays, such as Python lists or integer arrays
- Time and space cost in terms of `n` and `m`
- Why the row sums are only approximately zero in floating point
### Follow-up Questions
- Why does omitting `keepdims` break the subtraction, and does it always raise an error?
- How would you center columns instead of rows, and is `keepdims` still needed there?
- How would you also scale each row to unit standard deviation, and what happens to a constant row?
- How would you center rows that contain missing values stored as `NaN`?
Overview: Write a NumPy function that subtracts each row's mean from a 2-D array and returns a new array of the same shape. It tests axis-wise reductions, the keepdims argument, and how broadcasting aligns a column of row means with the original matrix.
Write center_rows(X) that subtracts each row's mean from that row of a 2-D NumPy array X. Return an array of the same shape, with each row summing to approximately zero.
The function must:
Reduce along
axis=1
with
keepdims=True
so the mean has shape
(n, 1)
and broadcasts against
X
.