Sub topic 11
Spotting missing data, wrong dtypes, and outliers
This chapter assumes you can already run head, info, and describe and read their basic output. You should also know that a column's dtype (its data type) controls which operations work on it. The goal here is to use those three methods as detectors. For each kind of problem, you will see which output line gives it away and which problems the output cannot show.
A messier DataFrame
The earlier examples used a tidy table. Real data usually arrives with problems, so this chapter uses a table with three planted ones: a missing value, a number stored as text, and an impossible age.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cleo", "Dev", "Eli", "Fay"],
"age": [34, 28, np.nan, 45, 39, 290],
"city": ["Lima", "Oslo", "Lima", "Pune", "Oslo", None],
"salary": ["52000", "48000", "61000", "75000", "58000", "n/a"],
"joined": ["2021-03-01", "2020-07-15", "2022-01-10",
"2019-11-30", "2023-05-02", "2021-08-19"],
})
df.info()
print(df.describe())Each method sees a different part of the damage. The sections below take the problems one at a time.
Missing data
What info shows
Look at the Non-Null Count column in the info output and compare each entry with the RangeIndex line. The index here has 6 entries. name, salary, and joined show 6 non-null. age and city show 5 non-null. Each of those two columns is missing exactly one value.
A short non-null count is the fastest missing-data check for a wide table. It works even when the data has hundreds of columns, because you only compare one number per column against the row count.
Counting and locating missing values
info tells you that values are missing, but not where. Use isna() for that. The next snippet keeps only the columns that have a gap, which keeps wide tables readable.
missing = df.isna().sum()
print(missing[missing > 0])
share = df.isna().mean().round(3)
print(share[share > 0])
print(df[df.isna().any(axis=1)])The first print shows a count of 1 for age and for city. The second shows the same gaps as a fraction of rows (about 0.167 here). The third prints the rows that contain at least one missing value, so you can see which people they belong to. The fraction matters more than the count when you decide what to do. One missing value in 6 rows is a very different problem from one in 6 million.
Missing values that look like data
The non-null count only recognizes real missing markers, which are NaN, None, and NaT. Every other placeholder counts as an ordinary value. Look at the salary column. It shows 6 non-null even though one entry is the string "n/a". Common placeholders that info will not flag include:
- Strings such as
"n/a","unknown","-", or an empty string"". - Sentinel numbers such as
-999,9999, or0used to mean "no value". - Whitespace-only strings.
You find these through head, describe, or value counts, not through info. A column that looks complete in info can still hold a lot of fake values.
Wrong dtypes
Reading the Dtype column
The Dtype column of info states what pandas believes each column holds. Compare it with what you expect:
| Column | Expected | Shown by info | Meaning |
|---|---|---|---|
| `age` | integer or float | `float64` | Correct. It is float because `NaN` cannot be stored in an integer column. |
| `salary` | numeric | `object` | Wrong. At least one entry is text, so every entry stays text. |
| `joined` | datetime | `object` | Wrong. The dates are plain strings. |
| `city` | text or category | `object` | Acceptable for a text column. |
In pandas 3 and in pandas 2 with string options enabled, text columns may appear as str or string instead of object. The reasoning is the same. A numeric or date column that shows a text dtype is wrong.
Why one bad value changes the whole column
A column has one dtype. The single "n/a" in salary forces pandas to keep the whole column as text, even though five of the six entries look like numbers. This is the most common cause of an object column that should be numeric. Two other signals point to the same problem:
describe()leaves the column out of its default output, because the default only covers numeric columns. If you expectedsalaryin the summary and it is absent, check its dtype.- Arithmetic fails or behaves strangely. Adding two text columns concatenates them instead of summing.
Converting and re-checking
Convert with pd.to_numeric and pd.to_datetime. Passing errors="coerce" turns anything that cannot be converted into NaN (or NaT for dates) instead of raising an error.
df["salary"] = pd.to_numeric(df["salary"], errors="coerce")
df["joined"] = pd.to_datetime(df["joined"])
df["city"] = df["city"].astype("category")
df.info()
print(df.describe())After the conversion, salary is float64 and joined is datetime64. The "n/a" became NaN, so the salary non-null count drops from 6 to 5. That is the correct result, because the missing value is now visible. It is also a good reason to run info again after every conversion. A conversion can turn silently wrong text into explicit gaps, and the non-null count shows how many.
Converting city to category is optional. It helps when a text column has few distinct values, and info(memory_usage="deep") will show the memory saving on a large table.
Outliers and suspicious ranges
An outlier is a value far from the rest of the column. It may be a real extreme or a data entry error. describe gives you the evidence to decide which, but it cannot decide for you.
Reading min, max, and the quartiles
For age, the five non-null values are 28, 34, 39, 45, and 290. The relevant describe rows are:
| Statistic | Value |
|---|---|
| count | 5.0 |
| mean | 87.2 |
| 25% | 34.0 |
| 50% | 39.0 |
| 75% | 45.0 |
| max | 290.0 |
Three signals stand out:
- The
maxof 290 is not a possible human age. A domain check like this needs no statistics. You only need to know what values are plausible. - The mean (87.2) is more than double the median (39.0). A few extreme values pull the mean far more than the median, so a large gap between the two suggests a skewed column or outliers.
- The distance from the 75% mark (45) to the max (290) is far larger than the distance from the min (28) to the 25% mark (34). A long tail on one side is visible directly in the percentile rows.
Also check count. It excludes missing values, so a count of 5 in a 6-row table repeats what info told you about missing data.
A rule for flagging candidates
Once describe raises suspicion, flag the rows with the interquartile range (IQR) rule. A value is a candidate outlier if it lies more than 1.5 times the IQR below the 25% mark or above the 75% mark.
q1, q3 = df["age"].quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
mask = (df["age"] < low) | (df["age"] > high)
print(df.loc[mask, ["name", "age"]])Here q1 is 34, q3 is 45, and the IQR is 11. The bounds are 17.5 and 61.5. The only row flagged is Fay with an age of 290. Missing values compare as False in both tests, so Cleo is not flagged.
Limits of this check
- The IQR rule flags candidates only. A value outside the bounds can be real, such as a very high salary. Decide using what you know about the data.
- A bad value inside the normal range is invisible. An age of 3 in an adult-only table passes every statistical test, and only a domain rule can catch it.
- Very small tables give unstable quartiles. With 5 values, one extreme point can move the bounds a lot, so treat the result as a hint.
- Outliers that are placeholders, such as
-999or9999, usually show up as an oddminormax. Aminof-999in a column of ages or prices is almost always a sentinel and not a measurement.
Summary of signals
| Problem | Where it shows | What to look for |
|---|---|---|
| Real missing values | `info` non-null count, `isna().sum()` | Non-null count below the row count |
| Placeholder text | `head`, `describe(include="all")` | Values like `"n/a"` or `"-"`, odd `top` entries |
| Sentinel numbers | `describe` min or max | `-999`, `9999`, or a block of zeros |
| Wrong dtype | `info` Dtype column | `object` for numbers or dates |
| Hidden numeric column | `describe` default output | Expected column missing from the summary |
| Outliers | `describe` | Mean far from median, max or min implausible |
Making the checks a routine
A reasonable order for a new table is: head to see real values, info for dtypes and non-null counts, isna().sum() for exact gaps, then describe for ranges. Fix dtypes first, because describe only summarizes numeric columns, and a column stuck as object will not show its range. After each fix, run info again. The aim is for each fix to change exactly the counts you expected and nothing else.
Exercise
A price column shows object as its dtype in info, and describe() leaves it out. You run pd.to_numeric(df["price"], errors="coerce") and the non-null count falls from 1000 to 940. What happened, and what should you do before keeping the result?
Show answer
Sixty entries could not be parsed as numbers, so errors="coerce" turned them into NaN. Those entries were probably placeholders or stray text, such as "n/a", currency symbols, or thousands separators like "1,200". Before keeping the result, find the affected rows (for example, select rows where the converted column is null but the original was not) and look at the raw values. If they are formatting problems, clean the strings and convert again. If they are real placeholders, keep them as missing.
Exercise
A weight_kg column has mean 71.4, median 68.0, min -999, and max 112. Which of these numbers suggests a problem, and why might the IQR rule still miss part of it?
Show answer
The min of -999 is a sentinel for "no measurement", not a weight. It also pulls the mean below what the median suggests. The IQR rule may flag -999, but the check should come from the domain: no weight can be negative. If many rows hold -999, they distort the quartiles too, which can widen the bounds and let other bad values through. Replace -999 with NaN, then run describe again.