Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

Auditing Raw Data Before You Model

Audit a raw table before training: find missing values hidden behind sentinel codes, invalid entries and messy labels, outliers that need a second look, duplicate rows that leak across splits, and columns that only exist after the prediction is made.

Contentsand lesson path

What you will learn

  • Audit a raw dataset for missing values, invalid entries, duplicates, outliers and columns that would not be available at prediction time.

01. Why it matters

A model learns whatever the table says, mistakes included. If 4% of distances hold the code -1, a linear model learns that some parcels travel minus one kilometre. If an export wrote some rows twice, those rows count double in training and can land on both sides of a train/test split, where the model is graded on rows it has already memorised. If a column is filled in only after delivery, the model scores brilliantly offline and fails on the first real booking, because that column does not exist yet when the prediction is made.

None of these problems raises an error: pandas reads the file, scikit-learn fits the model, and the score looks fine, or too good. That is why an audit comes before any modelling: a short, systematic pass over the raw data that asks five questions about every column.

  1. What is missing, including values that only look present?
  2. What is impossible or inconsistent?
  3. What is extreme, and is it an error or a rare truth?
  4. What is duplicated?
  5. When does this value become known, compared with the moment of prediction?

This lesson audits a raw export of 1,200 parcel bookings from a courier that wants to predict, at booking time, whether a parcel will arrive late. The script below builds the file with every defect above on purpose. The code was tested with Python 3.12, NumPy 2.5, pandas 3.1 and scikit-learn 1.9; run each script in the same folder.

Python · make_raw.py
"""Write parcels_raw.csv: 1,200 parcel bookings with the defects of a real export."""
import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
n = 1_200
booked = pd.Timestamp("2026-03-01") + pd.to_timedelta(rng.integers(0, 92 * 24 * 60, n),
                                                      unit="min")
weight = rng.lognormal(0.8, 0.6, n).round(2)
distance = rng.gamma(2.0, 9.0, n).round(1)
service = rng.choice(["standard", "express", "economy"], n, p=[0.6, 0.25, 0.15])
p_late = 1 / (1 + np.exp(-(-2.2 + 0.05 * distance + 0.9 * (service == "economy"))))
late = (rng.random(n) < p_late).astype(int)
delay = np.where(late == 1, rng.integers(15, 300, n), 0)

df = pd.DataFrame({
    "parcel_id": [f"P{i:05d}" for i in range(n)],
    "booked_at": booked.strftime("%Y-%m-%d %H:%M"),
    "weight_kg": weight,
    "distance_km": distance,
    "service": service,
    "delay_minutes": delay,  # written by the tracking system after delivery
    "refund_issued": ((late == 1) & (rng.random(n) < 0.6)).astype(int),
    "late": late,
})
# Defects: gaps, a sentinel code, impossible values, messy labels, a far outlier
df.loc[rng.choice(n, 36, replace=False), "weight_kg"] = np.nan
df.loc[rng.choice(n, 48, replace=False), "distance_km"] = -1.0  # "not geocoded"
df.loc[rng.choice(n, 5, replace=False), "weight_kg"] = 0.0
df.loc[rng.choice(n, 2, replace=False), "weight_kg"] = 1250.0  # grams typed as kg
df.loc[rng.choice(n, 9, replace=False), "service"] = "Express "
df.loc[rng.choice(n, 1, replace=False), "distance_km"] = 412.0
# A retry bug in the export wrote 60 rows twice
df = pd.concat([df, df.sample(60, random_state=7)]).sample(frac=1, random_state=7)
df.to_csv("parcels_raw.csv", index=False)
print(df.shape)
print(df.dtypes.to_string())
Expected output
(1260, 8)
parcel_id            str
booked_at            str
weight_kg        float64
distance_km      float64
service              str
delay_minutes      int64
refund_issued      int64
late               int64

The file has 1,260 rows, not 1,200: the first clue. Note also the dtypes: pandas 3 reads text columns as its dedicated str dtype, where pandas 2 showed object. booked_at is still plain text at this point; it is parsed and checked below.

02. Missing values, visible and disguised

Start with what pandas already counts as missing. NaN ("not a number") marks an empty value in numeric columns, and pandas 3 uses the same marker in str columns. isna() finds these.

Python · audit_missing.py
import numpy as np
import pandas as pd

df = pd.read_csv("parcels_raw.csv")
print("percent missing (NaN):")
print((df.isna().mean() * 100).round(1).to_string())

# A sentinel hides as a valid-looking number that repeats far too often
for col in ["weight_kg", "distance_km"]:
    top = df[col].value_counts().head(3).to_dict()
    print(f"most frequent {col}: {top}")

print("mean distance_km with the -1 codes:", round(df["distance_km"].mean(), 2))
df["distance_km"] = df["distance_km"].replace(-1.0, np.nan)
print("mean distance_km without them:   ", round(df["distance_km"].mean(), 2))
share = df["distance_km"].isna().mean()
print("percent missing distance_km now: ", round(share * 100, 1))
Expected output
percent missing (NaN):
parcel_id        0.0
booked_at        0.0
weight_kg        3.0
distance_km      0.0
service          0.0
delay_minutes    0.0
refund_issued    0.0
late             0.0
most frequent weight_kg: {1.29: 13, 1.66: 12, 1.28: 10}
most frequent distance_km: {-1.0: 48, 19.9: 10, 11.8: 10}
mean distance_km with the -1 codes: 17.68
mean distance_km without them:    18.42
percent missing distance_km now:  3.8

The first table says only weight_kg has gaps (3.0%). That is not the whole truth. Systems that cannot store an empty value often write a sentinel code instead: a valid-looking value with a special meaning, such as -1, 0, 999, 9999, 1900-01-01 or the text unknown. A sentinel gives itself away in two ways. It is impossible or implausible for the column (a distance cannot be negative), and it repeats far more often than any genuine value. Here -1.0 appears 48 times; the next most common distance, 10 times.

Left as numbers, sentinels distort everything computed from the column. The mean distance moves from 17.68 to 18.42 km once the codes are removed, and a code such as 999 would move it much further. A linear model would fit its slope through those fake points. Replace each sentinel with NaN, so that your tools treat it as what it is: an unknown value. Confirm the meaning with the data owner if you can, because the same number can be a code in one column and real in another: zero items in a parcel is impossible, zero previous orders is common.

Missingness itself can carry information. Addresses that cannot be geocoded may be rural ones, and rural parcels may be late more often. So when you fill in (impute) a value later, keep a missing indicator: a 0/1 column that records that the value was absent. The next lesson measures what that indicator is worth to a model.

03. Invalid entries and outliers

An invalid entry breaks a rule that the data must satisfy. The rules come from the business, not from statistics: this courier takes parcels above 0 kg and up to 30 kg, a booking time lies inside the export period, and a service label is one of three known names.

Python · audit_values.py
import pandas as pd

df = pd.read_csv("parcels_raw.csv")

# Rules come from the business: a parcel weighs more than 0 and at most 30 kg
w = df["weight_kg"]
print("weight <= 0:  ", int((w <= 0).sum()))
print("weight > 30:  ", int((w > 30).sum()), w[w > 30].tolist())

# Labels that should be one category
print("raw service labels:", df["service"].value_counts().to_dict())
clean = df["service"].str.strip().str.lower()
print("after strip/lower: ", clean.value_counts().to_dict())

# Timestamps: parse, then check the range
booked = pd.to_datetime(df["booked_at"], format="%Y-%m-%d %H:%M")
print("booked_at range:", booked.min(), "to", booked.max(), "| dtype", booked.dtype)

# Outliers: compare the tail with the bulk before deciding anything
d = df["distance_km"].where(df["distance_km"] >= 0)
q1, q3 = d.quantile([0.25, 0.75])
fence = q3 + 1.5 * (q3 - q1)
print("distance quantiles 50/99/max:",
      d.quantile(0.5).round(1), d.quantile(0.99).round(1), d.max())
print(f"above the IQR fence ({fence:.1f} km):", int((d > fence).sum()))
Expected output
weight <= 0:   5
weight > 30:   2 [1250.0, 1250.0]
raw service labels: {'standard': 734, 'express': 315, 'economy': 202, 'Express ': 9}
after strip/lower:  {'standard': 734, 'express': 324, 'economy': 202}
booked_at range: 2026-03-01 04:58:00 to 2026-05-31 22:11:00 | dtype datetime64[us]
distance quantiles 50/99/max: 15.1 60.0 412.0
above the IQR fence (48.8 km): 36

Five parcels weigh 0 kg and two weigh 1,250 kg, which is probably 1.25 kg typed in grams. Both are impossible, so treat them as missing too, unless the data owner can give you the correction. The service column has a fourth label, 'Express ' with a capital letter and a trailing space. An encoder would treat it as a separate category, so normalise text labels with str.strip().str.lower() before you count categories. Parsing booked_at with an explicit format raises an error on any malformed string, a free validity check. pandas 3 stores the parsed times as datetime64[us] (microseconds) where pandas 2 used nanoseconds, so code that turns timestamps into integers must not assume nanoseconds.

An outlier is a value far from the bulk of the data. It may be an error or a rare but real case; the audit's job is to tell the two apart, not to delete everything unusual. A common screen is the interquartile range (IQR) fence: values more than 1.5 times the IQR above the third quartile are flagged. Here it flags 36 distances above 48.8 km. Most are simply long trips, and removing them would teach the model that long trips do not exist. Only the 412 km parcel deserves a question to the operations team. When extreme values are real, prefer methods that tolerate them, such as trees, a robust scaler or a log transform.

04. Duplicates and what they do to a split

An exact duplicate is a row that appears more than once with identical values in every column. Export retries, a file loaded twice and joins on keys that are not unique all create them. A second kind shares a key that should be unique, such as parcel_id, while other columns differ; those need a rule for which version wins.

Python · audit_dupes.py
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

df = pd.read_csv("parcels_raw.csv")
print("exact duplicate rows:   ", int(df.duplicated().sum()))
print("repeated parcel_id:     ", int(df.duplicated("parcel_id").sum()))

# What a random split does with the copies
X = df[["weight_kg", "distance_km"]].fillna(-99)
train, test = train_test_split(df.index, test_size=0.25, random_state=0)
train_ids = set(df.loc[train, "parcel_id"])
seen = df.loc[test, "parcel_id"].isin(train_ids)
print("test rows with a copy in train:", int(seen.sum()), "of", len(test))

tree = DecisionTreeClassifier(random_state=0).fit(X.loc[train], df.loc[train, "late"])
hit = tree.predict(X.loc[test]) == df.loc[test, "late"]
print(f"accuracy on copied test rows: {hit[seen.to_numpy()].mean():.2f}")
print(f"accuracy on unseen test rows: {hit[~seen.to_numpy()].mean():.2f}")

dedup = df.drop_duplicates()
print("rows after drop_duplicates():", len(dedup))
Expected output
exact duplicate rows:    60
repeated parcel_id:      60
test rows with a copy in train: 22 of 315
accuracy on copied test rows: 1.00
accuracy on unseen test rows: 0.65
rows after drop_duplicates(): 1200

The export wrote 60 rows twice. Their extra weight in training is the smaller problem. A random split puts copies on both sides: 22 of 315 test rows have an identical twin in the training set. A fully grown decision tree simply remembers them, scoring 1.00 on those rows against 0.65 on the others. The overall test accuracy blends the two groups, so it overstates how the model will do on parcels it has never seen.

Remove exact duplicates with drop_duplicates() before you split. Some repetition is legitimate: one customer sends many parcels. Those rows are not duplicates, but they are related, and a model can learn the customer rather than the pattern. When that matters, use a group-aware split such as GroupKFold, which keeps all rows of one group in the same fold. The skill Model Evaluation and Validation covers split design in depth.

05. Columns from after the prediction

The most expensive defect is a column whose value is not known when the prediction is made. This is target leakage: information about the outcome reaches the model through a feature. The model looks excellent in validation and then meets production, where the column is empty or does not exist yet.

The test is a timeline. For each column, ask when its value is written, and compare that with the moment of prediction, which here is booking time. weight_kg, distance_km and service are known at booking. delay_minutes is written by the tracking system after delivery and is the target in another form. refund_issued is decided after a late delivery. Both must go, however predictive they look. A quick screen helps you find candidates: score each column on its own against the target.

Python · audit_leaks.py
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score

df = pd.read_csv("parcels_raw.csv").drop_duplicates()
df["distance_km"] = df["distance_km"].replace(-1.0, np.nan)

# Screen: how well does each numeric column rank late parcels on its own?
for col in ["weight_kg", "distance_km", "delay_minutes", "refund_issued"]:
    ok = df[col].notna()
    auc = roc_auc_score(df.loc[ok, "late"], df.loc[ok, col])
    print(f"{col:<14} single-column AUC {max(auc, 1 - auc):.3f}")
Expected output
weight_kg      single-column AUC 0.503
distance_km    single-column AUC 0.672
delay_minutes  single-column AUC 1.000
refund_issued  single-column AUC 0.815

AUC is the area under the ROC curve: 0.5 means the column ranks late and on-time parcels no better than chance, and 1.0 means it separates them perfectly. A single column that comes close to 1.0 is either a leak or a sign that the problem is trivial, and it is rarely the second. Here delay_minutes reaches 1.000 and refund_issued 0.815, far above the honest features. The screen only points; the timeline decides. A leaky column can also look modest, for example a partly filled count of support calls made after booking, so check the meaning of every column.

Write the audit as code, not notes: the same checks then run on every new export, and the cleaning rules they lead to can move into the model's pipeline, which lesson 4 builds.

06. Check your understanding

Practice check · 3 questions

Audit decisions

Each question has one best answer.

Q1. After `drop_duplicates()`, 25 `parcel_id` values still appear twice, each pair with different `weight_kg` values. What should the audit do next?
Q2. The `service` column holds 'express' 315 times and 'Express ' (capital E, trailing space) 9 times. If the audit skips it, what does `OneHotEncoder` make of these values?
Q3. In `audit_dupes.py` the tree scored 1.00 on test rows with a copy in training and 0.65 on the others. Which figure is the honest estimate for new parcels?
Practice only: not graded, not saved, not evidence.

07. Apply it

Start the skill's practice project now. Choose a mixed-type dataset with numeric, categorical, datetime and free-text columns, or extend make_raw.py with a date and a text column, and write audit.py, which prints:

  • the share of NaN per column and the three most frequent values of each numeric column, so that sentinels stand out;
  • the number of rows that break each business rule you can state;
  • exact duplicates, and duplicates on the key column;
  • a single-column AUC (or a correlation, for a numeric target) for every candidate feature.

Then note, for every column, when its value becomes known relative to the prediction, and your decision: keep, convert a sentinel to missing, fix, or drop.

08. Review prompt

Without looking back, answer in your own words:

  1. Name two signs that a value is a sentinel code rather than a real measurement.
  2. Why must duplicates be removed before the train/test split rather than after it?
  3. The IQR fence flagged 36 distances. Why were most of them kept?
  4. Which question decides whether a column leaks, and why can a single-column AUC not decide it alone?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check