Missing Values
Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 45 of 60.
Real data has gaps: a sensor fails, a quiz is missed. pandas marks each empty cell NaN, "not a number":
Most models refuse NaN, so count the gaps first. .isna() marks each one True, and .sum() counts them:
scores = pd.DataFrame({
"name": ["Ana", "Ben", "Cy", "Dee"],
"quiz1": [8, np.nan, 7, 9], # np.nan is a gap
"quiz2": [6, 5, np.nan, np.nan],
})
print(scores.isna().sum())This prints:
name 0
quiz1 1
quiz2 2
dtype: int64Then choose: dropna() drops every row with a gap; fillna(0) writes 0 into each. Both return a new table, so store it.
Statistics skip NaN: the mean of quiz1 is 8.0, from its three known scores.
Challenge
MediumA fitness tracker missed some readings in tracker.csv. Before training, see how each way of handling gaps moves the average sleep. The starter reads hours, a fill value.
- Print the gaps in each column.
- Print the mean sleep, rounded to 2 decimals, three ways: skipping gaps, over days with no gap in any column, and with gaps filled with
hours.
For another tracker and 8:
day 0
steps 1
sleep 2
water 0
dtype: int64
Skipping gaps: 6.9
Complete days only: 7.0
Gaps filled with 8.0: 7.21Try it yourself
import pandas as pd
tracker = pd.read_csv("tracker.csv")
hours = float(input())
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature Grid3Array Math
Math on Whole ArraysSummary StatisticsStatistics by AxisBroadcastingBoolean MasksRecap: Exam Scores9Grouping and Cleaning
Counting ValuesGrouping DataSeveral SummariesMissing ValuesRecap: Survey ResultsPractice on your own: Online Python compiler