# 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())
