Sub topic 6
Auditing missing values, duplicates, and odd values
This chapter covers the audit step of an EDA. You look for data problems and write them down, but you don't fix anything yet. Fixing comes in the next chapter. I assume you know basic Python and pandas DataFrames, have run cells in Jupyter, and know the mean, the median, and what a distribution is. The code continues from the earlier chapters: df_raw is the untouched orders table loaded with pd.read_csv, and pd, np, and display are available.
Why audit before cleaning
A cleaning rule written before an audit is a guess. You might drop rows with missing values and later find that 40% of one column was blank, so the rule deleted a large share of your data. The audit gives you the size and shape of each problem. It also produces a written list of decisions to make.
Keep the audit separate from the cleaning in the notebook, in its own section. A reader can then see what was wrong with the data, and which cleaning step answers each problem.
A reusable quality report
Start with a function that summarizes every column in one table. It returns a DataFrame, so it works on any table and you can call it again after cleaning to compare the two.
def quality_report(df):
return pd.DataFrame({
"dtype": df.dtypes.astype(str),
"missing": df.isna().sum(),
"missing_pct": (df.isna().mean() * 100).round(1),
"n_unique": df.nunique(),
})
display(quality_report(df_raw))
print("duplicate rows:", df_raw.duplicated().sum())Read the table column by column. Four things to look for:
- A
dtypeofobjecton a column that should be numeric or a date. This often means some values are text, such as"N/A"or"$12.50". - A high
missing_pct. Note it even if it is small, because the pattern of the gaps matters more than the count. - An
n_uniqueof 1. The column carries no information. - An
n_uniqueequal to the row count. The column is probably an identifier.
Missing values
Count them, then ask why they are missing
isna() finds NaN and None. It does not find placeholders such as "unknown", "-", an empty string, or -999. Those look like real values and slip past the report above. Check for them explicitly, for example by listing the most common values in each text column.
text_cols = df_raw.select_dtypes(include="object").columns
for col in text_cols:
print(col)
print(df_raw[col].value_counts(dropna=False).head(8))
print()dropna=False keeps NaN in the counts, so you see it next to the other values. If you find placeholders, record them in your log. A later cleaning step converts them to real missing values.
Look for patterns in the gaps
Whether values are missing at random changes what you can safely do. Compare the missing rate across groups to check.
missing_amount = df_raw["amount"].isna()
print(missing_amount.groupby(df_raw["region"]).mean().round(3))
print(missing_amount.groupby(df_raw["order_date"].dt.to_period("M")).mean().round(3))If the missing rate is 2% in every region and every month, the gaps probably look like noise. If one region has 30% missing, or all the gaps start in one month, something happened in the data pipeline. For example, a system change or a new data source may have stopped recording the value. Dropping those rows would then remove a whole region from your analysis. Write this kind of pattern down, because it limits which conclusions you can trust later.
Missing values in other columns
Check whether columns are missing together. Two columns that are always missing in the same rows usually come from the same source.
cols_with_gaps = df_raw.columns[df_raw.isna().any()]
print(df_raw[cols_with_gaps].isna().corr().round(2))A correlation near 1 between two missingness columns means the gaps coincide.
Duplicates
df.duplicated() marks a row as a duplicate when every column matches an earlier row. The count in the quality report covers only this case. Two other cases need separate checks.
- Exact duplicates. The whole row repeats. Usually a load or export error.
- Key duplicates. An identifier such as
order_idrepeats, but other columns differ. This may be an update, a correction, or two different records sharing an ID. - Near duplicates. The same entity with small differences, such as
"North"and"north ". Exact checks miss these until the text is normalized.
print("exact duplicates:", df_raw.duplicated().sum())
key_dupes = df_raw[df_raw.duplicated("order_id", keep=False)]
print("rows sharing an order_id:", len(key_dupes))
display(key_dupes.sort_values("order_id").head(10))keep=False marks every member of a duplicate group, not only the later copies. That lets you view the whole group side by side. Sorting by the key puts the copies next to each other, so you can see which columns differ.
To check for near duplicates, normalize text in a temporary copy and compare counts before and after.
raw_regions = df_raw["region"].nunique()
norm_regions = df_raw["region"].str.strip().str.lower().nunique()
print(f"region labels: {raw_regions} raw, {norm_regions} after normalizing")If the second number is smaller, some labels differ only in case or whitespace. Record this. The cleaning function from the next chapter handles it.
The choice between "keep the first", "keep the last", and "merge" depends on what the duplicate means. Whether the data has a timestamp column that shows which record is newer is a question for the audit log, not something to guess.
Odd values
Odd values are present and have the right type, but they are implausible or inconsistent. No single function finds them. You use domain knowledge to decide what is plausible, then test it.
Ranges and impossible values
Start with the summary statistics for numeric columns, and look at the minimum and maximum.
display(df_raw.describe().T[["min", "50%", "mean", "max"]])
print("negative amounts:", (df_raw["amount"] < 0).sum())
print("zero amounts:", (df_raw["amount"] == 0).sum())
print("future orders:", (df_raw["order_date"] > pd.Timestamp.today()).sum())Each line checks one rule. Write the rules as plain statements before you code them: "amounts should not be negative", "order dates should not be in the future". A count of zero is a useful result. It means the rule holds.
A gap between the median and the mean, or a maximum far above the median, points to extreme values. An extreme value is not automatically an error. A large order may be real. Treat it as a question for the log, and check whether it is a typo (an extra zero), a unit mix-up, or a legitimate big customer.
Spotting outliers with a simple rule
The interquartile range (IQR) rule flags values far outside the middle half of the data. It is a prompt to look, not a verdict.
q1, q3 = df_raw["amount"].quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
flagged = df_raw[(df_raw["amount"] < low) | (df_raw["amount"] > high)]
print(f"flagged {len(flagged)} of {len(df_raw)} rows outside [{low:.2f}, {high:.2f}]")
display(flagged.sort_values("amount").tail(5))On a right-skewed column like order amounts, this rule flags many legitimate high values. The number it prints depends on the shape of the data, so read the flagged rows before you decide anything.
Categories and text
For category columns, list every distinct value. Misspellings, mixed case, and unexpected labels show up quickly.
print(sorted(df_raw["region"].dropna().unique()))Short lists are easy to scan. For long ones, look at the rarest values with value_counts().tail(10), because typos tend to appear once or twice.
Consistency across columns
Some problems appear only when you compare columns. A ship_date before its order_date, or a quantity of 3 with a total that does not match price times quantity, are examples. Write each relationship as a boolean test and count the failures. Use only the columns that exist in your data.
Recording the audit
End the audit section with a markdown cell that lists each problem, how many rows it affects, and a proposed action. The Evidence line should point to the cell above. The numbers are examples.
### Audit summary
| Issue | Rows affected | Proposed action |
| --- | --- | --- |
| Exact duplicate rows | 112 | Drop, keep first |
| Missing `amount` | 4.2% | Drop for amount analysis; check region pattern |
| Region labels differ by case and spaces | 3 extra labels | Strip and lowercase |
| Negative `amount` | 17 | Investigate; likely refunds |Each row in this table should map to one line in clean_orders in the next chapter. If a problem has no matching action, the log is incomplete. If a cleaning rule has no matching problem, ask why it is there.
Common mistakes
- Trusting
isna()alone. Placeholders such as"unknown"and-999count as present. - Cleaning while auditing. Overwriting
df_rawhides the original problem. Keep every audit check reading fromdf_raw. - Checking only counts. A column with 3% missing values can still have all of them in one region.
- Treating flagged outliers as errors. A rule gives a candidate. A reason makes it an error.
- Skipping the recheck. After cleaning, call
quality_reporton the cleaned table and compare it to the raw report.
Exercise
A column discount has 0% missing values in quality_report, but its dtype is object and its minimum shown by value_counts().tail() includes the text "none". Why did the report show no missing values, and what should you record in the audit log?
Show answer
isna() only detects real NaN or None, and the text "none" is an ordinary string, so it was counted as present. Record that discount uses "none" as a placeholder for missing, give the number of rows with that value, and propose converting it to a real missing value (or to 0, if "no discount" is the true meaning) in the cleaning step. Also note that the column is not numeric until it is converted.
Exercise
You find that order_id appears twice for 40 orders, and the two rows differ only in status ("pending" and "shipped"). Is drop_duplicates() the right fix? What would you check first?
Show answer
No. drop_duplicates() with no arguments only removes rows identical in every column, so it would not remove these rows. These are key duplicates, probably the same order recorded at two points in time. Check whether a timestamp or update column shows which row is newer. If one exists, keep the latest row per order_id. Record the decision in the audit log.