Replace NaN and Infinite Values in a NumPy Array With np.nan_to_num
Quick Overview
Write a NumPy function that returns a float array with NaN replaced by 0 and positive or negative infinity replaced by the dtype's largest finite values, using np.nan_to_num. It tests how NumPy handles non-finite values, float dtype limits, and returning a copy without changing the input.
Replace NaN and Infinite Values in a NumPy Array With np.nan_to_num
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `clean(a: np.ndarray) -> np.ndarray` that returns a float array with every non-finite value replaced by a finite one.
The function must:
- Return a float array with no `NaN` or infinite values.
- Map `NaN` to `0.0`, `+inf` to the dtype's largest finite value, `-inf` to its most negative finite value.
- Use `np.nan_to_num` (defaults) for the replacement.
```python
a = np.array([1.0, np.nan, np.inf, -np.inf])
clean(a)
# array([ 1.00000000e+000, 0.00000000e+000, 1.79769313e+308, -1.79769313e+308])
```
```hint Mind the dtype
The largest finite value depends on the float type. Think about which dtype your result should have when the input is `float32`, and whether your function changes the caller's array.
```
### Constraints & Assumptions
- `a` is a real-valued float array.
### What a Strong Answer Covers
- The default replacement `np.nan_to_num` makes for `NaN`, `+inf` and `-inf`, and where the infinity replacements come from.
- Which float dtype the result has, including for a `float32` input.
- Returning a new array so the input is not modified.
- What happens to finite values.
### Follow-up Questions
- The output is finite, but what can still go wrong in later arithmetic when `+inf` becomes the largest finite float?
- How would you map `NaN`, `+inf` and `-inf` to values of your choice, and when would dropping or flagging these entries be better?
- How would you replace non-finite values in a 2-D array with each column's mean instead of a constant?
Overview: Write a NumPy function that returns a float array with NaN replaced by 0 and positive or negative infinity replaced by the dtype's largest finite values, using np.nan_to_num. It tests how NumPy handles non-finite values, float dtype limits, and returning a copy without changing the input.