Cleaning data
- Machine Learning course
- Beginner
- Lesson 38/112
- 7 min
Detect and clean missing data.
Filling the gaps
There are two empty cells: the humidity of day 2 and the temperature of day 3. Dropping the rows would lose 40% of the data; instead we'll fill each column with its own mean. np.nanmean takes the mean while ignoring nans:
print(np.nanmean(veri, axis=0)) # [ 3. 23. 48.75]
print(veri.mean(axis=0)) # [ 3. nan nan] nan is contagiousAny operation involving nan gives nan, which is why nan-safe functions are needed.
Filling selectively with np.where
np.where(condition, a, b) takes from a where the condition is true and from b otherwise. Thanks to broadcasting, the column means are applied to every row:
ort = np.nanmean(veri, axis=0)
veri = np.where(np.isnan(veri), ort, veri)
print(np.isnan(veri).sum()) # 0In scikit-learn, SimpleImputer(strategy="mean") does the same; here you saw its logic by hand.
Practice Clean
Fill the nan values in veri using np.nanmean(veri, axis=0) and np.where. Print the temperature column (veri[:, 1]) and the humidity column (veri[:, 2]) on separate lines.
Starter code
import io
import numpy as np
csv = "gun,sicaklik,nem\n1,20,40\n2,22,\n3,,60\n4,26,50\n5,24,45\n"
veri = np.genfromtxt(io.StringIO(csv), delimiter=",", skip_header=1)
# buraya yazSample solution
import io
import numpy as np
csv = "gun,sicaklik,nem\n1,20,40\n2,22,\n3,,60\n4,26,50\n5,24,45\n"
veri = np.genfromtxt(io.StringIO(csv), delimiter=",", skip_header=1)
ort = np.nanmean(veri, axis=0)
veri = np.where(np.isnan(veri), ort, veri)
print(veri[:, 1])
print(veri[:, 2])Expected output
[20. 22. 23. 26. 24.] [40. 48.75 60. 50. 45. ]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>np.array([1, np.nan, 3]).mean()</code> give?
- 2.0
- 1.33
- An error
- nan Correct answer
Explanation: A sum containing nan becomes nan; nanmean would give 2.0.
2 Take the column means ignoring nan values.
ort = np.____(veri, axis=0)
ort = np.nanmean(veri, axis=0)
Explanation: nanmean is the mean of the non-nan values.
3 Match the functions.
| Term | Meaning |
|---|---|
np.nanmean |
Mean without nan |
np.where |
Conditional selection |
np.isnan |
nan mask |
x.mean() |
Returns nan if nan exists |