|
| 1 | +# NumPy: Handling NaN and Infinity |
| 2 | + |
| 3 | +This section of the repository demonstrates how to detect and replace special numerical values such as **NaN (Not a Number)** and **Infinity** using NumPy. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## 📌 Detecting NaN (Not a Number) values |
| 8 | +```python |
| 9 | +import numpy as np |
| 10 | + |
| 11 | +arr = np.array([1, 2, np.nan, 5, 6, np.nan, 33]) |
| 12 | +print(np.isnan(arr)) |
| 13 | +# Output: [False False True False False True False] |
| 14 | +``` |
| 15 | +Use `np.isnan()` to return a boolean array indicating the positions of `NaN` values. |
| 16 | + |
| 17 | +--- |
| 18 | + |
| 19 | +## 📌 Replacing NaN values |
| 20 | +```python |
| 21 | +cleaned_arr = np.nan_to_num(arr, nan=4) |
| 22 | +print(cleaned_arr) |
| 23 | +# Output: [ 1. 2. 4. 5. 6. 4. 33.] |
| 24 | +``` |
| 25 | +Use `np.nan_to_num(array, nan=value)` to replace all NaNs with a specific value (default is 0). |
| 26 | + |
| 27 | +--- |
| 28 | + |
| 29 | +## 📌 Detecting Infinity values |
| 30 | +```python |
| 31 | +arrinf = np.array([1, 2, np.inf, 5, 6, -np.inf, 33]) |
| 32 | +print(np.isinf(arrinf)) |
| 33 | +# Output: [False False True False False True False] |
| 34 | +``` |
| 35 | +`np.isinf()` returns a boolean array where `True` represents either `+inf` or `-inf`. |
| 36 | + |
| 37 | +--- |
| 38 | + |
| 39 | +## 📌 Replacing Infinity values |
| 40 | +```python |
| 41 | +replaced_inf = np.nan_to_num(arrinf, posinf=10, neginf=-10) |
| 42 | +print(replaced_inf) |
| 43 | +# Output: [ 1. 2. 10. 5. 6. -10. 33.] |
| 44 | +``` |
| 45 | +Use `np.nan_to_num()` to handle infinite values as well using `posinf` and `neginf` parameters. |
| 46 | + |
| 47 | +--- |
| 48 | + |
| 49 | +## ✅ Summary |
| 50 | +- `np.isnan()` → Detects NaN |
| 51 | +- `np.nan_to_num()` → Replaces NaN or infinite values with specified defaults |
| 52 | +- `np.isinf()` → Detects infinity (`+inf`, `-inf`) |
| 53 | + |
| 54 | +These utilities are essential for data cleaning and preparing numerical data for machine learning or statistical analysis. |
0 commit comments