Missing value in Python — 10 Essential Steps to Better Data
Find a Missing value in Python, build a SimpleImputer workflow for delivery records, and learn how to keep estimated values visible in a planning dashboard.
Harborline Parcel is a fictional courier that handles deliveries across Central, North, and Riverside. Its planning team is preparing a weekly dashboard when the latest export arrives with gaps. Some records have no delivery duration, some have no parcel weight, and some have no service type. The dashboard expects those fields to be populated. If the team simply drops incomplete rows, it may hide how much work each zone handled. If it treats blanks as zeros, an incomplete record can look like an instant delivery or a weightless parcel.
The team has an export of 300 deliveries in reporting order. The first 240 belong to the historical reference period, and the last 60 form the current batch. Each row has a delivery ID and a zone. The main measurements are minutes and kilograms, and the service type records the booked tier. Earlier records contain gaps as well, but they give the team observed examples it can use as a starting point. Managers also want to see where current duration gaps tend to occur so they can investigate the capture process.
Deliver a complete working copy for the planning dashboard and a short data-quality report. Keep the original log available for audit, preserve which duration entries were missing, and recommend the first zone to investigate. Make the limits of estimated values clear to anyone using the dashboard.
02
Your role
▥
YOUR ASSIGNMENT
Operations Data Analyst
You are the Operations Data Analyst supporting Harborline’s reporting team. Your first responsibility is to separate missing data from unusual but valid values. You will check each field, measure how common its gaps are in the current batch, and find out whether duration gaps are concentrated in one zone. Then you will choose an approach that fits both numeric measurements and service labels.
Prepare reproducible Python code that learns replacement values from the historical period and applies them to the current batch. Keep IDs and row order intact, and preserve an indicator that tells readers which durations were filled. Your handover should include a before-and-after check, the values used to fill gaps, and a recommendation for improving capture.
03
Identify the problem
What is the core reporting problem, and which data preparation method would you use?
Identify the business outcome, suitable technique and why you would choose it.
Expert Problem Formulation
The core issue is incomplete reporting data. A missing value in Python represents a gap in the export, which may result from a failed scan, a skipped field, or an upstream processing issue. The team needs an analysis-ready copy with all 60 current deliveries and enough detail to tell observed durations apart from estimates.
Use pandas to identify the missing cells and scikit-learn’s SimpleImputer to learn replacements. The median is the middle of the ordered observations and works well as a baseline when rare, long deliveries pull the mean upward. The most frequent service type is a simple categorical baseline. A zero-minute fill would look like a real, very fast delivery. Dropping incomplete rows would remove valid delivery IDs from planning totals.
Fit the replacement rules on historical rows and reuse them on the current batch. This keeps the current batch from influencing the rules applied to it and makes the workflow suitable for repeated reporting. For each field, the learned statistic uses the available historical observations.
The expected outputs are a cleaned table, missing counts and percentages, learned fills, and a zone-level breakdown of missing durations. After validating these outputs, recommend where to inspect the collection process first. A completed dashboard can support planning while flagged estimates stay out of any report that requires measured delivery times.
04
Investigate
Ask the right questions before developing your solution.
Q01Which business outcome should the cleaned table support?
The team needs a planning view that includes every delivery and preserves a link to the original log. Use the current batch as the unit of reporting, and count missing values separately for duration, weight, and service tier. The business question about capture is narrower: which zone contributes the most missing duration records this week? Treat duration quality as its own issue because delivery time may inform staffing. Keep any imputed duration visibly flagged so that a downstream report can distinguish measured values from estimates when evaluating a delivery promise.
Q02What does a blank mean in each field?
A blank duration means the export lacks a recorded number of minutes. A blank weight means the parcel measurement is absent, and a blank service tier means the booked category was not recorded in the export. Check the data contract for other missing markers such as whitespace or sentinel values before using this procedure in production. pandas normally reads the empty fields here as missing. Treat an unusual measured value as a separate issue that requires domain checks. Start by checking unique delivery IDs and by keeping the historical and current sections in their original reporting order.
Q03Why choose two different imputation strategies?
Choose a method that matches the type of each column. Duration and weight are numeric, so their historical medians provide simple replacement values. A median is less influenced than a mean by a few extreme observations, such as deliveries delayed for an extended period. Service type is text, so the most frequent category gives the baseline replacement. Use two SimpleImputer objects because each has one strategy setting. Fit both using only the historical portion, then transform the current portion. Review unusual historical distributions separately because a single typical value can hide important differences among routes or service tiers.
Q04How do we know the repair did what we intended?
Compare the current counts before and after transformation. Divide each before count by the current batch size and multiply by 100 to get a field-level missing percentage. A record may contain multiple gaps, so adding the three counts measures missing cells. Verify that the three after counts are zero, the row order and IDs are preserved, the observed values are unchanged, and the duration flag matches the original mask. These checks validate the transformation. To estimate the quality of individual replacements, a separate backtest could hide observed historical values or compare fills with later recovered records.
Q05How should operations act on the duration flags?
Group the original duration flag by zone and count the true values. This shows where the missing records came from before any imputation made the table look complete. Direct the first investigation to the zone with the largest count because that is where a review can cover the most flagged cases immediately. In a production report, check the percentage alongside the count because large zones may naturally contribute more gaps. Ask whether capture failures follow a driver workflow, device, or handoff step. Treat a concentration as a starting point for investigation, and keep estimated durations separate from contractual performance records.
05
Project resources
▤
delivery_quality.csv
CSV · 300 deliveries · 5 fields · historical and current batches
First five current-batch records. An em dash marks an empty field.
delivery_id
zone
duration_min
weight_kg
service_type
D0241
Central
51
6.7
Standard
D0242
North
50
7.6
—
D0243
Riverside
42
0.5
Express
D0244
Central
26
3.9
Express
D0245
North
43
4.8
Standard
delivery_id identifies the delivery. zone marks its service area. duration_min is the recorded delivery time in minutes. weight_kg is the measured parcel weight in kilograms. service_type is the booked tier. The first 240 rows form the historical batch and the last 60 form the current batch.
06
Topic Lesson — Missing value in Python
Explore the topic through interactive visual learning.
TOPIC LESSON
01 / 10
FOUNDATIONS
What a missing value represents
A missing value in Python marks a cell for which we lack a usable observation. pandas can build a true-or-false mask from a table, and SimpleImputer can use a reference table to learn a replacement for each selected column. The resulting working table has estimates where the measurements were absent. Preserve the mask for any field whose original status matters. The small example shows how a reported duration differs from an estimated one.
isna() → True for missing cells
Key takeaway: An imputed value is an estimate. Preserve its original missing status.
CHOOSING A METHOD
Use a rule that fits the field
For a numeric field with occasional unusually large values, the median provides a stable starting point. A categorical label needs a category, so choose the most frequent observed label if the business allows it. A fixed ‘Unknown’ label can be better when an estimate would be misleading. If missing durations cluster by route, assess whether a single value fits every route and investigate the collection process before relying on resulting averages.
Numeric → median
Category → most frequent
Key takeaway: Choose the strategy by data type and reporting purpose.
FIT AND TRANSFORM
Learn once, then apply
SimpleImputer works one column at a time. During fit, it scans the observed historical values in each column and stores one statistic per field. During transform, it substitutes that statistic only in missing cells and preserves observed values. Imagine that the historical weight median is 4 kilograms and the current batch contains a 2-kilogram parcel and an unknown weight. The 2 stays in place and the missing weight gets 4.
fit(history) → learned value
transform(current) → filled rows
Key takeaway: Use fit to learn the rule and transform to apply it.
WORKFLOW
Keep reporting periods separate
Load the records in reporting order and create separate historical and current tables. Read the current missing mask before any values change. Use historical measurements to fit two imputers, then apply both to a copy of the current table. Add the original duration flag to that copy. Compare the result with the raw batch and publish the counts alongside the table so that a dashboard reader can see where values were estimated.
History → fit → rules
Current → audit → apply → verify
Key takeaway: Learn the rules from an earlier period and audit the current batch.
MATHEMATICS
Calculate median, mode, and missing rate
Sort observed numbers before selecting the median. For an even count, average the two middle numbers. For 22, 30, 46, and 90, those numbers are 30 and 46, giving 38. The mode is the category with the largest count. For Standard, Express, Standard, the mode is Standard. For a missing rate, divide the number of missing cells in a field by the number of rows. In this project, 17 of 60 durations are missing.
Key takeaway: Use observed values to learn a fill, and all current rows as the rate denominator.
PYTHON · LEARN
Configure and fit a numeric imputer
The import line loads the SimpleImputer class from scikit-learn. The second line constructs an imputer and selects the median strategy. The third line passes historical numeric columns in a two-dimensional DataFrame, which lets scikit-learn learn each column separately. For categories, repeat the same workflow using a separate object and the most frequent strategy. Keep the input columns in the same order whenever you apply either object.
# Import the scikit-learn tool that learns replacement values.
from sklearn.impute import SimpleImputer
# Choose the median as the replacement for each numeric field.
num = SimpleImputer(strategy="median")
# Learn each numeric column’s median from historical deliveries.
num.fit(history[numeric])
Key takeaway: A fitted imputer holds a statistic for each input column.
PYTHON · APPLY
Write estimates into a working copy
The first line creates a copy of the current table. The second line applies the learned numeric estimates and assigns the returned rectangular array back to the same measurement columns. The third line adds the original duration mask as an audit flag. Repeat the transform and assignment for the category field with its own fitted imputer. Save the mask before transformation because the filled measurements themselves cannot identify the original gaps.
# Copy current deliveries so the original observations remain available.
clean = current.copy()
# Fill missing durations and weights with their historical medians.
clean[numeric] = num.transform(current[numeric])
# Flag deliveries whose duration was originally missing.
clean["duration_imputed"] = missing["duration_min"]
Key takeaway: Preserve the raw current table and carry the original mask forward.
VALIDATION
Check completeness and preservation
Compare each field’s missing count before and after the fill. In the current batch, durations drop from 17 gaps to zero, weights from 6 to zero, and service types from 12 to zero. Check that the row labels and order still match. The exercise also compares every repaired record with the reference, which catches changes to observed values. For a production accuracy study, mask known observations or compare estimates with recovered scans.
Missing after = clean[fields].isna().sum()
Key takeaway: Zero remaining blanks confirms completeness. Measure accuracy separately.
INTERPRETATION
Spot a concentration of missing durations
Riverside contributes 10 of the 17 missing durations. Central contributes 3 and North contributes 4. All three contribute 20 current records, so Riverside also has the highest missing percentage at 50 percent. A common fill of 38 minutes can flatten variation and pull summaries toward a typical historical value. A quick scan of the cleaned values alone would hide that capture risk. Use the original flags to make the gap visible in any planning view.
Riverside = 10 / 20 = 50%
Key takeaway: The audit flags reveal where an apparently complete dashboard needs scrutiny.
ACTION
Start with the Riverside capture workflow
Put Riverside first in the operations review because it has the most missing duration records in this batch. Compare flagged delivery IDs with pickup and completion events, and ask the zone supervisor whether a device or handoff misses the final scan. Let planners see the filled working table alongside the flag counts and let performance reports use only measured durations where exact timing is required. Check new batches after any capture fix before judging whether coverage improved.
Prioritize → trace events → track missing rate
Key takeaway: Repair the reporting copy and investigate the upstream source.
1 / 10 slides explored
07
Build the solution
Complete the missing Python operations and run your analysis.
Audit and repair the current delivery batch
Fill each blank with one Python identifier. Use the hint beside a line when you need a clue. The dataset loads automatically when you submit your code.
delivery_repair.py0 / 25 filled
# Import pandas to read and inspect the delivery records.
01import as pd
# Import the scikit-learn tool that learns replacement values.
# Import pandas to read and inspect the delivery records.
import pandas as pd
# Import the scikit-learn tool that learns replacement values.
from sklearn.impute import SimpleImputer
# Load the delivery quality CSV into a DataFrame.
log = pd.read_csv("delivery_quality.csv")
# Check that each delivery ID appears only once.
assert log["delivery_id"].is_unique, "Duplicate delivery ID"
# Use the first 240 rows as historical data for learning replacements.
history = log.iloc[:240].copy()
# Reserve the remaining rows as the current deliveries to repair.
current = log.iloc[240:].copy()
# Group duration and weight as numeric fields and service type as a category.
numeric, categorical = ["duration_min", "weight_kg"], ["service_type"]
# Combine the field lists for the missing-value audit.
fields = numeric + categorical
# Mark each missing cell in the selected current fields.
missing = current[fields].isna()
# Count the missing cells in each field before filling them.
before = missing.sum()
# Express each missing count as a percentage of current deliveries.
rates = before.div(len(current)).mul(100)
# Count missing durations in each delivery zone.
by_zone = missing.groupby(current["zone"])[numeric[0]].sum()
# Choose the median as the replacement for each numeric field.
num = SimpleImputer(strategy="median")
# Choose the most frequent historical category for each categorical field.
cat = SimpleImputer(strategy="most_frequent")
# Learn each numeric column’s median from historical deliveries.
num.fit(history[numeric])
# Learn the most frequent service type from historical deliveries.
cat.fit(history[categorical])
# Copy current deliveries so the original observations remain available.
clean = current.copy()
# Fill missing durations and weights with their historical medians.
clean[numeric] = num.transform(current[numeric])
# Fill missing service types with the historical most frequent value.
clean[categorical] = cat.transform(current[categorical])
# Flag deliveries whose duration was originally missing.
clean["duration_imputed"] = missing[numeric[0]]
# Count how many missing cells remain in each repaired field.
after = clean[fields].isna().sum()
# Verify that all target cells are filled and row indices are preserved.
assert after.sum() == 0 and clean.index.equals(current.index), "Check repair"
# Display original missing counts and rates rounded to two decimal places.
print("Current missing:", before.to_dict(), "| %:", rates.round(2).to_dict())
# Display the replacement values learned from historical data.
print("Historical fills:", num.statistics_.tolist(), cat.statistics_.tolist())
# Report remaining missing counts and originally missing durations by zone.
print("Remaining:", after.to_dict(), "| Duration flags by zone:", by_zone.to_dict())
Complete code walkthrough
LINE 01
Import the table library
# Import pandas to read and inspect the delivery records.
import pandas as pd
pandas provides the DataFrame, a table with labeled rows and columns. The import binds the short name pd in the program so that a later call to pd.read_csv can read the delivery export. The alias is a convention in Python data work and keeps expressions short.
This statement prepares the tools and prints nothing. Later lines use pandas to detect blanks, count them, and assign the estimated values back under the original column names.
LINE 02
Load the imputer class
# Import the scikit-learn tool that learns replacement values.
from sklearn.impute import SimpleImputer
The from statement imports SimpleImputer from scikit-learn’s impute module. A class is a recipe for building an object. Here each object can learn one replacement per column based on a strategy you choose.
Importing the class alone does not read or fill any data. Later you will create two objects, one for the measurements and another for service labels. They have independent learned values.
LINE 03
Read the delivery log
# Load the delivery quality CSV into a DataFrame.
log = pd.read_csv("delivery_quality.csv")
read_csv opens the named CSV file and builds a DataFrame with the first row as the column names. With the defaults used here, empty fields come in as missing. pandas typically represents missing numeric cells with NaN, so an integer duration column with gaps may be stored as decimal numbers.
The result is stored in log and keeps the file’s row order. If you run this file locally, use the folder that contains the CSV as your working directory.
LINE 04
Check the delivery identifiers
# Check that each delivery ID appears only once.
assert log["delivery_id"].is_unique, "Duplicate delivery ID"
Selecting delivery_id with one column label returns a Series, which is a one-dimensional labeled collection. Its is_unique property returns a Boolean indicating whether every value appears once. An assert raises an AssertionError with the supplied message if the condition is false.
Duplicated IDs could cause operations staff to investigate the same delivery twice. Uniqueness checks for repeated identifiers. A production import should also check that IDs are present and follow the expected format.
LINE 05
Select the historical rows
# Use the first 240 rows as historical data for learning replacements.
history = log.iloc[:240].copy()
iloc selects rows by integer position. The slice starts at zero by default and stops before position 240, so it takes the first 240 deliveries. Calling copy makes an independent working DataFrame for that reference period.
The row order is part of this export’s reporting contract. A different file may require sorting by a verified timestamp or selecting the reference period with a date filter before fitting an imputer.
LINE 06
Select the current batch
# Reserve the remaining rows as the current deliveries to repair.
current = log.iloc[240:].copy()
The second slice starts at position 240 and continues to the end. It selects the final 60 records and preserves their original row labels. The copy makes later experimentation with the current batch independent of the import.
The split simulates the point when a previously defined reporting rule meets fresh data. If you change the batch definition, review the missing percentages and the historical baselines before comparing reports.
LINE 07
Separate numeric and text columns
# Group duration and weight as numeric fields and service type as a category.
numeric, categorical = ["duration_min", "weight_kg"], ["service_type"]
The two lists describe the inputs to the two strategies. duration_min and weight_kg hold quantities, and service_type holds labels such as Standard. The comma between the two expressions allows Python to unpack both lists into the corresponding variables in one statement.
The identifiers and zone are kept outside the lists because this exercise audits those columns without estimating them. A median over service-tier text would not be a meaningful operation.
LINE 08
Combine the fields for auditing
# Combine the field lists for the missing-value audit.
fields = numeric + categorical
The plus operator concatenates Python lists. fields therefore holds duration_min, weight_kg, and service_type in that order. A DataFrame indexed with a list returns another DataFrame, which is convenient when computing the same check across several columns.
The separate lists still control the input to each imputer. Reusing the combined list for both audit checks gives you comparable before and after counts even though the fields are filled with different rules.
LINE 09
Capture the current missing mask
# Mark each missing cell in the selected current fields.
missing = current[fields].isna()
isna returns a Boolean DataFrame with the same rows and columns as the selected data. A true cell marks a gap, and a false cell marks an available value. This captures all three fields at the same stage before any replacement happens.
Store this mask as missing because the filled table alone cannot show which values were estimated. The duration column of this mask will later become the reporting flag and the input to the zone audit.
LINE 10
Count the gaps by field
# Count the missing cells in each field before filling them.
before = missing.sum()
DataFrame.sum works down each column by default. For Boolean values, true contributes one and false contributes zero. The output is a Series indexed by the column names, with 17 for duration, 6 for weight, and 12 for service type.
These counts track cells. One delivery can contribute to several columns when it has several gaps. Use a row-level any check separately if you need the number of affected deliveries.
LINE 11
Convert counts to percentages
# Express each missing count as a percentage of current deliveries.
rates = before.div(len(current)).mul(100)
len(current) gives the number of current records, 60. div divides each element of the before Series by that count, and mul multiplies the resulting fractions by 100. The operations preserve the field labels.
For example, 17 divided by 60 and multiplied by 100 gives about 28.33 percent. All current rows belong in the denominator because the metric describes the fraction of records missing a given field.
LINE 12
Audit the duration gaps by zone
# Count missing durations in each delivery zone.
by_zone = missing.groupby(current["zone"])[numeric[0]].sum()
groupby partitions the Boolean table using current’s zone labels, which share the same row index. The bracket expression selects the first numeric field, duration. Summing that grouped Series counts missing duration cells for Central, North, and Riverside.
Riverside has ten flags, compared with four in North and three in Central. All three zones have twenty current records. In an uneven batch, use both the counts and rates to interpret the concentration.
LINE 13
Choose a median for the measurements
# Choose the median as the replacement for each numeric field.
num = SimpleImputer(strategy="median")
The strategy parameter tells SimpleImputer how to learn its replacements. With median, each numeric column gets its own middle observed value. An even number of observations gives a median halfway between the two middle numbers.
The median is useful here because a few unusually long deliveries can pull an average upward. At this point, num is configured but unfitted. Once it has seen history, it can apply its learned rules.
LINE 14
Choose the most frequent service label
# Choose the most frequent historical category for each categorical field.
cat = SimpleImputer(strategy="most_frequent")
The most_frequent strategy selects the value with the largest observed count in each included column. It can handle categorical strings such as the three service tiers. In a tie, SimpleImputer chooses the smallest tied value under its ordering.
This choice gives the planning table a usable label where the booking type is absent. Repeatedly choosing the most common tier can inflate its share, so the original export remains important for any count by recorded service tier.
LINE 15
Learn the measurement replacements
# Learn each numeric column’s median from historical deliveries.
num.fit(history[numeric])
history[numeric] selects the historical duration and weight columns as a two-dimensional DataFrame. fit reads the observed values in each column and records its median, which here is 38 minutes for duration and 3.95 kilograms for weight.
The current batch does not enter this calculation. Keeping it separate avoids letting the input being audited influence the estimates applied to it. An entirely empty historical field needs a separate decision about whether and how it can be filled.
LINE 16
Learn the service replacement
# Learn the most frequent service type from historical deliveries.
cat.fit(history[categorical])
history[categorical] uses a one-item list, so the input is still a two-dimensional table. The fitted categorical imputer counts observed service labels in that historical table and stores Standard as the fill value for the service column.
Passing just the column name would return a Series and can cause an input shape error. The list also preserves the same column-selection pattern used for numeric measurements and makes it clear which input the imputer expects.
LINE 17
Create a separate repaired copy
# Copy current deliveries so the original observations remain available.
clean = current.copy()
current.copy creates a DataFrame with the same current values, index, and columns. The program assigns it to clean before applying any replacements. This keeps the source available when you want to compare the same delivery before and after repair.
Reusing the same variable for raw and repaired data makes that comparison harder. A working copy also lets you add audit columns while the raw batch and its original fields stay available.
LINE 18
Apply the historical numeric fills
# Fill missing durations and weights with their historical medians.
clean[numeric] = num.transform(current[numeric])
transform applies num’s fitted medians to the current numeric columns. It returns a two-dimensional array with the same row order. Assignment writes its values to the two named columns in clean, replacing only the missing entries in the input.
A missing duration receives 38 minutes and a missing weight receives 3.95 kilograms. Use the same column order as fit to keep each statistic paired with the correct measurement. The console summary later lets you verify which statistics were used.
LINE 19
Apply the historical category fill
# Fill missing service types with the historical most frequent value.
clean[categorical] = cat.transform(current[categorical])
The categorical transform uses the earlier service frequencies to replace current blanks with Standard. Assigning its array to the list of categorical columns keeps the text values in the correct destination alongside the numeric fields.
A delivery originally marked Express keeps its label. The most common label is a reporting estimate for a missing field. Operations should recover the booked tier from source events when individual delivery decisions depend on it.
LINE 20
Record an original duration flag
# Flag deliveries whose duration was originally missing.
clean["duration_imputed"] = missing[numeric[0]]
numeric[0] is the column label duration_min. Selecting that column from missing returns a Boolean Series indexed by the original current row labels. Assigning the Series creates the duration_imputed field in clean and aligns the values with matching row labels.
A row now carries both a usable value and a flag indicating whether it was estimated. This makes it possible for a performance report to filter out filled duration values while a planning report keeps all current records.
LINE 21
Count missing cells after repair
# Count how many missing cells remain in each repaired field.
after = clean[fields].isna().sum()
The code selects the audited fields from clean and calls isna again. Summing the new mask produces the remaining gap count for each field. All three counts are zero in the verified run because the historical reference supplied a usable statistic for each column.
This check measures completeness of the working copy. A separate comparison should confirm that valid observed values stayed fixed, and recovered observations are needed to judge the precision of specific estimates.
LINE 22
Reconcile completeness and row order
# Verify that all target cells are filled and row indices are preserved.
assert after.sum() == 0 and clean.index.equals(current.index), "Check repair"
The first condition sums the remaining field counts and requires zero. The second compares the cleaned index with the original current index using equals. The and operator requires both conditions to pass. A failure stops the script with a Check repair error.
These checks guard against introducing gaps or dropping or reordering row labels. The exercise grader also compares the full repaired records, so an incorrect value or flag cannot pass just because the labels and row count match.
LINE 23
Print the current audit
# Display original missing counts and rates rounded to two decimal places.
print("Current missing:", before.to_dict(), "| %:", rates.round(2).to_dict())
to_dict converts each field-indexed Series into a dictionary, making its labels visible in the console. round(2) rounds the percentages for display while rates retains its full-precision values for evaluation. Python’s print separates the labels and the dictionaries with spaces.
Readers can compare a field’s number of missing records with its share of the batch. In this output, about 28.33 percent of duration values were absent before repair.
LINE 24
Print the learned baselines
# Display the replacement values learned from historical data.
print("Historical fills:", num.statistics_.tolist(), cat.statistics_.tolist())
statistics_ is an attribute available once the imputer is fitted. The trailing underscore is a scikit-learn convention for an attribute learned from data. tolist converts each NumPy array to an ordinary Python list so its contents are easy to read in the console.
The numeric list follows the original column order, so 38.0 corresponds to duration and 3.95 to weight. The categorical list contains Standard. Save these values with the historical date range in a production handover.
LINE 25
Print the remaining gaps and zone flags
# Report remaining missing counts and originally missing durations by zone.
print("Remaining:", after.to_dict(), "| Duration flags by zone:", by_zone.to_dict())
The last statement prints both the remaining field counts and the previously computed duration gaps by zone. The zone figures come from the original current mask, so the numbers stay meaningful after the repair has filled durations in the reporting copy.
This is the business handover: the remaining gap counts establish completeness and the original flags point to Riverside for the first capture review. Retain both summaries so dashboard readers can see the difference between coverage and estimated completeness.
The cleaned copy supports planning across all 60 current deliveries. The pipeline fills 35 missing cells across three fields, using 38 minutes, 3.95 kilograms, and Standard as the historical baselines. Multiple gaps can occur in one row, so 35 is a cell count. The working copy retains the original order and flags every duration estimate.
Riverside accounts for ten of the seventeen missing durations even though the three zones handled equal volumes in the current batch. Replacing so many missing values with one number could mask meaningful differences in Riverside’s service times. The audit shows where to investigate, but neither the counts nor the filled values can reveal the actual durations or the cause of the missing records.
BUSINESS RECOMMENDATION
50% missing durations
Riverside capture review
10 of 20 current Riverside deliveries lack a recorded duration
Start with Riverside’s capture process. Ten of its twenty current delivery records lack a duration, which makes Riverside the first place to check. Have the zone lead compare the flagged IDs with dispatch and completion events, look for missing scan timestamps, and report whether gaps concentrate around a device, a handoff, or a particular shift.
Use the cleaned table for provisional planning with imputed durations visibly flagged. For contractual reporting or individual delivery investigations, use measured durations and report coverage alongside them. After a capture improvement, compare Riverside’s before-fill missing rate over several comparable batches. A lower rate would show better coverage, while a backtest or recovered observations would be needed to judge how close the 38-minute estimate was.
08
End of the lesson
Reflect on your learning experience.
How was your learning experience?
Select a rating
Explore more lessons
Continue building practical skills with other interactive labs.
APPLIED DATA ANALYTICS
Data cleaning in python — 10 Essential Steps to Better Data
Practice Data cleaning in python on warehouse receipts. Inspect data types, fix inconsistent values, remove duplicates, and verify dock totals in a hands-on lab.
Data Joining in python — 3 Essential Checks for Better Parcel Pricing
Data Joining in python with pandas. Stack parcel manifests, merge zone tariffs, verify every shipment and reconcile delivery charges in an interactive coding lab.
Group by data analysis in Python: 10 Powerful Steps to Success
Learn Group by data analysis in Python through 10 visual lessons, a real-world retail project, pandas exercises, revenue summaries and profit analysis.
Pivot data analysis in Python — 10 Practical Steps to Better Decisions
Learn Pivot data analysis in Python with 10 visual lessons. Build pandas pivot tables from dispatch records, check late rates, and recommend a depot review.