Section 4 · Lesson 3
Missing values and dates
Find, count and fill missing values, and turn text dates into real dates for time-based analysis.
Two things make real datasets harder than textbook ones: gaps and dates. In our
data, 6 campaigns have no end_date, 18 customers never gave an age_group, and 264
orders have no campaign_id. Meanwhile every date column is stored as text. This lesson
deals with both.
What missing looks like
An empty cell in a CSV becomes NaN (“not a number”) when pandas loads it. It means
unknown, not zero, and it behaves differently from any real value:
import pandas as pd
customers = pd.read_csv("customers.csv")
customers["age_group"].isna() # True where missing
customers["age_group"].notna() # True where present
customers.isna().sum() # missing count for every column
customers["age_group"].isna().mean() # share missing (0.06 = 6%)
How missing values affect calculations
Most aggregations skip NaN by default:
pd.Series([10, None, 30]).sum() # 40.0
pd.Series([10, None, 30]).mean() # 20.0 (average of the 2 known values)
pd.Series([10, None, 30]).count() # 2 (count ignores missing)
len(pd.Series([10, None, 30])) # 3
Also, NaN == NaN is False, so never test for missing values with ==; always use
isna().
Deciding what to do
There’s no single right answer. It depends on what the gap means for the business:
| Column | Why it’s missing | Sensible handling |
|---|---|---|
campaigns.end_date |
campaign is always-on | keep it; treat as “still running” |
customers.age_group |
customer skipped the question | label it "unknown" |
orders.campaign_id |
sale not attributed to a campaign | keep the order; label or report separately |
Dropping rows is the bluntest tool. Dropping the unattributed orders would erase almost a third of revenue.
fillna and dropna
customers["age_group"] = customers["age_group"].fillna("unknown") # replace missing values
orders = pd.read_csv("orders.csv")
attributed = orders.dropna(subset=["campaign_id"]) # drop rows missing campaign_id only
Both return a new object, so assign the result to keep it. Always pass subset= to
dropna: without it, a row missing any column is removed.
Older tutorials often write df["col"].fillna(value, inplace=True). Under pandas 3’s
copy-on-write rules, that fills a temporary copy and leaves df unchanged (you’ll see a
ChainedAssignmentError warning). Assign the result back instead, as above.
Turning text into dates
read_csv loads dates as plain text (str). Convert them with pd.to_datetime:
orders["order_date"] = pd.to_datetime(orders["order_date"])
orders["order_date"].dtype # datetime64
Now the .dt accessor unlocks date parts:
| Code | Example result |
|---|---|
.dt.year |
2026 |
.dt.month |
2 |
.dt.day |
14 |
.dt.day_name() |
'Saturday' |
.dt.to_period("M") |
2026-02 |
Filtering and grouping by date
Dates compare naturally, and you can compare them with date strings:
march = orders[orders["order_date"] >= "2026-03-01"]
orders.groupby(orders["order_date"].dt.month)["amount"].sum()
orders.groupby(orders["order_date"].dt.day_name())["id"].count() # orders by weekday
Date arithmetic
Subtracting two dates gives a duration; .dt.days turns it into a number:
campaigns = pd.read_csv("campaigns.csv")
campaigns["start_date"] = pd.to_datetime(campaigns["start_date"])
campaigns["end_date"] = pd.to_datetime(campaigns["end_date"]) # missing stays missing (NaT)
campaigns["duration_days"] = (campaigns["end_date"] - campaigns["start_date"]).dt.days
Always-on campaigns get NaN for duration_days, which is exactly right: their duration
isn’t known yet. A missing date is shown as NaT (“not a time”).
Tip: Run
df.isna().sum()and checkdf.dtypeson every new dataset, right afterhead(). Gaps and text-typed dates are the two most common reasons an analysis returns a wrong number without any error.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Fill in missing age groups
DoneLoad customers.csv into customers. Some customers never told us their age.
1. Set missing_age to the number of customers whose age_group is missing (an integer). 2. Replace the missing values in the age_group column of customers with the text "unknown", so that the column has no missing values left. Don't drop any rows.
Need a hint?
customers["age_group"].isna()is True where the value is missing;.sum()counts them.fillna("unknown")returns a new Series; assign it back withcustomers["age_group"] = ....
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
customers = pd.read_csv("customers.csv")
missing_age = 0
# fill the missing age groups here
print(missing_age)
print(customers["age_group"].value_counts(dropna=False))
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)Completed revenue by month
DoneLoad orders.csv into orders.
1. Convert the order_date column of orders to real dates with pd.to_datetime. 2. Create monthly_revenue: a Series with the total amount of completed orders for each month, rounded to 2 decimals. Its index should be the month number (1, 2, 3), which is what .dt.month gives you.
Need a hint?
orders["order_date"] = pd.to_datetime(orders["order_date"])converts text to dates.- Filter to completed orders, then group by
completed["order_date"].dt.month. - Finish with
["amount"].sum().round(2).
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
orders = pd.read_csv("orders.csv")
monthly_revenue = None
print(orders.dtypes)
print(monthly_revenue)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)