Compute a Pearson Correlation Matrix in NumPy
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `correlation_matrix(data: np.ndarray) -> np.ndarray`. Given a 2-D array with variables in rows and observations in columns, return the `n × n` Pearson correlation matrix computed with `np.corrcoef`, where n is the number of rows.
Requirements:
- Entry `[i, j]` is the correlation between variables `i` and `j` (symmetric).
- Diagonal entries equal `1` and all entries lie in `[-1, 1]`.
For example:
```python
data = np.array([[1.0, 2.0, 3.0, 4.0],
[4.0, 3.0, 2.0, 1.0]])
correlation_matrix(data)
# array([[ 1., -1.],
# [-1., 1.]])
```
```hint Which axis holds the variables
Check which axis `np.corrcoef` treats as the variables by default, and confirm the output is n by n with n equal to the number of rows.
```
```hint Degenerate inputs
Look at the definition of Pearson correlation and ask what it does when a row is constant, and what `np.corrcoef` returns when there is only one row.
```
### What a Strong Answer Covers
- A function that returns an n by n matrix with the variables taken from the rows, checked against the example.
- Why the matrix is symmetric, has ones on the diagonal and stays within `[-1, 1]`, from the definition of correlation as normalized covariance.
- Floating-point behavior: diagonal values that come out a rounding error away from 1, and how to test results.
- Degenerate inputs such as a constant row, a single variable and fewer than two observations.
### Follow-up Questions
- How would you handle a variable with zero variance (a constant row)?
- How would you compute this without `np.corrcoef`?
- What changes if the data has observations in rows and variables in columns, as in a typical DataFrame?
- How would you handle missing values in `data`?
Overview: Implement a NumPy function that returns the Pearson correlation matrix of a 2D array whose rows are variables and columns are observations. It tests array orientation, correlation as normalized covariance, and handling of constant rows and floating-point rounding.