Sub topic 6
Checking for duplicate rows and implausible values
This chapter assumes you can load a CSV with read_csv, build boolean masks, and read the output of describe and info. It also assumes the earlier chapters' habit of looking at the data before computing anything on it. The goal is to decide whether the table can be trusted before you compare groups or plot anything.
Why validity checks come early
Missing values show up in info. Duplicates and impossible values don't, because they look like normal data. A repeated row inflates a count. A negative age or a ticket price of zero pulls a mean in a direction you won't notice later. Checking costs a few lines, and it is much cheaper than discovering the problem after you have drawn a conclusion.
There are two kinds of check:
- Structural checks ask whether rows are repeated and whether an identifier column really identifies one row.
- Plausibility checks ask whether each value is allowed (a category from a known set) and sensible (a number in a believable range).
Neither kind proves the data is correct. They only find problems you can name in advance, so write the rules down from what you know about the domain.
Finding duplicate rows
DataFrame.duplicated() returns a boolean Series. A row is True if an identical row appeared earlier in the table. By default every column must match, and the first occurrence is not marked.
import pandas as pd
df = pd.read_csv("train.csv")
print("duplicate rows:", df.duplicated().sum())
print("PassengerId unique:", df["PassengerId"].is_unique)On the Titanic training file both checks come back clean: zero duplicated rows, and PassengerId is unique. That result is less informative than it looks. PassengerId is a row counter, so it differs in every row. Two records of the same person would carry different ids and would never be flagged as full-row duplicates.
To catch that case, compare everything except the id:
content_cols = df.columns.drop("PassengerId")
print("duplicates ignoring PassengerId:", df.duplicated(subset=content_cols).sum())subset takes a list of column names (an Index works too). Here it is also zero. Real data often isn't this tidy, so keep the check in your routine.
Choosing the right definition of "duplicate"
What counts as a duplicate depends on what a row represents. In this table a row is one passenger, so the natural key is the person, and Name is the closest thing to a person identifier:
print("repeated names:", df.duplicated(subset="Name").sum())Two people can share a name in other datasets, so a repeated key is a prompt to look, not proof of an error.
Repeats that are legitimate
Some columns are supposed to repeat. Ticket is a good example, because families and groups traveled on one ticket:
shared = df[df.duplicated(subset="Ticket", keep=False)]
print("rows sharing a ticket:", len(shared))
print(shared.sort_values("Ticket")[["Ticket", "Name", "Fare", "Cabin"]].head(8))The argument keep=False marks every member of a repeated group, including the first one. The default, keep="first", marks only the later copies. Use keep=False when you want to read the whole group, and the default when you want a count of surplus rows.
Look at the Fare column for people on the same ticket. In this data the same fare often appears for every member of a group. That raises a question for later chapters: is Fare a per-person price or a per-ticket price? You found it by checking a "duplicate" that turned out to be real structure.
If you do decide that exact duplicates are errors, df.drop_duplicates() returns a new DataFrame and leaves df unchanged. Assign it to a new name, and print the row counts before and after.
Checking categories against allowed values
For a column with a fixed set of valid values, list those values and use isin to find anything else. value_counts(dropna=False) from the previous chapter shows the same thing for a single column. isin makes the rule explicit and countable, which is better when you have several columns to check.
allowed = {
"Survived": [0, 1],
"Pclass": [1, 2, 3],
"Sex": ["male", "female"],
}
for col, values in allowed.items():
bad = ~df[col].isin(values)
print(f"{col}: {bad.sum()} values outside {values}")
bad_port = df["Embarked"].notna() & ~df["Embarked"].isin(["C", "Q", "S"])
print("Embarked: unexpected non-missing values:", bad_port.sum())The Embarked check needs the extra notna() condition. A missing value is not in the allowed list, so isin would flag it as bad. Missing values were already counted in the previous chapter, so this check is limited to values that are present but unexpected.
A common failure in text columns is inconsistent spelling: "Male", "male ", "M". Those show up as extra entries in value_counts(). Titanic's Sex is clean, but if you meet this elsewhere, df[col].str.strip().str.lower() is the usual first repair.
Checking numeric ranges
For numeric columns, start with the minimum and maximum. They are the fastest way to spot values outside any believable range.
print(df[["Age", "Fare", "SibSp", "Parch"]].agg(["min", "max"]))Read the output against what you know:
Ageruns from a fraction of a year (about 0.42) to 80. Fractional ages below 1 are infants measured in parts of a year, which is plausible. Nothing is negative, and nothing is above any believable human age.Farehas a minimum of 0 and a maximum above 500. The maximum is a long way from the typical fare, but the table contains first-class tickets, so it may be real. The zero needs a closer look.SibSp(siblings and spouses aboard) andParch(parents and children aboard) are small whole numbers. A largeSibSpis believable for a big family.
Turn your rules into masks so that each check gives a count you can record:
checks = {
"Age below 0 or above 100": (df["Age"] < 0) | (df["Age"] > 100),
"Age under 1 year": df["Age"] < 1,
"Fare of exactly 0": df["Fare"] == 0,
"Fare below 0": df["Fare"] < 0,
"SibSp or Parch below 0": (df["SibSp"] < 0) | (df["Parch"] < 0),
}
for name, mask in checks.items():
print(f"{name}: {mask.sum()}")A comparison against a missing value gives False, so rows with no Age are not counted by these masks. That is the right behavior here, since missing ages were handled separately. Remember it when you read the counts: a count of zero means "no present value broke the rule", not "all rows passed".
Inspect before you decide
A count tells you that something is there. Look at the rows before deciding what it is:
zero_fare = df.loc[df["Fare"] == 0, ["Name", "Pclass", "Fare", "Embarked"]]
print(len(zero_fare))
print(zero_fare.head())There are 15 zero-fare rows, and they are spread across classes. A free ticket can be real, for example crew traveling or a guest of the line, and it can also be a placeholder for an unknown price. The data alone cannot settle this. Both readings are plausible, so the honest choices are:
- Keep and note it. Any summary of
Fareincludes 15 zeros. Say so when you report averages. - Flag it. Add a boolean column such as
df["FareZero"] = df["Fare"] == 0, so you can include or exclude these rows later without changingFare. - Treat as missing. Replace the zeros with
NaNonly if you have a reason to think they mean "unknown".
Flagging is usually the best default at this stage, because it is reversible and keeps the raw column intact.
Cross-column checks
Some problems are visible only when two columns are compared. A rule such as "an infant should not be traveling with zero relatives" does not apply here, because infants could travel with a nanny or a family friend. Pick rules that must be true, not ones that merely usually hold. One that must hold: the number of passengers sharing a ticket cannot be smaller than what SibSp and Parch imply for related passengers on that ticket, but verifying this needs more work than a first pass deserves. Start with simple rules and add them as questions arise.
Common mistakes
- Checking only for full-row duplicates and ignoring the identifier or a business key.
- Dropping repeated values in columns where repetition is expected.
- Forgetting that comparisons with missing values return
False, so "zero violations" may hide rows you have not examined. - Fixing values in place. Make a flagged column or a new DataFrame so the raw data stays available.
- Not writing the check down. A rule you applied but did not record cannot be repeated or reviewed.
Exercise
Write code that reports how many passengers share their Ticket with at least one other passenger, and prints the three most common ticket values with their counts. Then explain in one sentence why you should not drop these rows as duplicates.
Show answer
Use shared = df.duplicated(subset="Ticket", keep=False) and print shared.sum(). For the common tickets, use print(df["Ticket"].value_counts().head(3)). Do not drop them because each row is a different passenger and the shared ticket reflects a real group traveling together. Only the Ticket column repeats, and removing those rows would delete real people from the analysis.
Exercise
A column Age has a missing value in row 5. The mask df["Age"] > 100 returns what for that row, and why does this matter when you report "0 implausible ages"?
Show answer
It returns False, because comparing a missing value with a number gives False. The count of 0 therefore covers only rows that have an age. Rows with a missing age were not tested, so you should say "0 implausible ages among the rows where Age is present".