Skip to content

Commit 97cb6e0

Browse files
Handling missing data using numpy
1 parent c5de78a commit 97cb6e0

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

Handling Missing Values/README.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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.

Handling Missing Values/nan.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'''
2+
Finding Nan values
3+
'''
4+
import numpy as np
5+
arr=np.array([1,2,np.nan,5,6,np.nan,33])
6+
7+
print(np.isnan(arr))
8+
9+
'''
10+
Nan to num
11+
np.nan_to_num(array,nan=value) default is 0
12+
'''
13+
14+
cleaned_arr=np.nan_to_num(arr,nan=4)
15+
print(cleaned_arr)
16+
17+
'''
18+
Identifying infinity values
19+
use np.isinf()
20+
'''
21+
arrinf=np.array([1,2,np.inf,5,6,-np.inf,33])
22+
print(np.isinf(arrinf))
23+
24+
'''
25+
replacing infinite values
26+
'''
27+
28+
print(np.nan_to_num(arrinf,posinf=10,neginf=-10))

0 commit comments

Comments
 (0)