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.

35 min 3 practice tasks
How do I handle missing values in pandas? by Data School on YouTube

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 check df.dtypes on every new dataset, right after head(). 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.

1

Fill in missing age groups

Load 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?
  1. customers["age_group"].isna() is True where the value is missing; .sum() counts them.
  2. fillna("unknown") returns a new Series; assign it back with customers["age_group"] = ....
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
2

How many orders are unattributed?

Load orders.csv into orders. An order with a missing campaign_id was not attributed to any campaign.

1. Set unattributed_pct to the percentage of orders with a missing campaign_id, rounded to 1 decimal (e.g. 12.3 for 12.3%). 2. Create attributed: a DataFrame with only the orders that do have a campaign_id (all columns).

Need a hint?
  1. The mean of a True/False Series is the share of Trues: orders["campaign_id"].isna().mean().
  2. orders.dropna(subset=["campaign_id"]) drops rows missing that one column.
  3. orders[orders["campaign_id"].notna()] works too.
Python 3
import pandas as pd

orders = pd.read_csv("orders.csv")

unattributed_pct = 0
attributed = orders

print(unattributed_pct, len(attributed))
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
3

Completed revenue by month

Load 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?
  1. orders["order_date"] = pd.to_datetime(orders["order_date"]) converts text to dates.
  2. Filter to completed orders, then group by completed["order_date"].dt.month.
  3. Finish with ["amount"].sum().round(2).
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country