Sub topic 6
Checking for Duplicate Rows and Implausible Values
This chapter assumes you can load train.csv into a DataFrame called df (see the earlier chapters) and that you know basic pandas indexing. The goal is to check whether the table contains repeated rows or values that cannot be right, before you summarize anything.
Why validity checks come early
Duplicate rows inflate counts and shift averages. Impossible values, such as a negative age, distort means and plots. Both are cheap to check and expensive to miss, so run these checks right after your first look at the data and before you compute statistics.
Counting duplicate rows
df.duplicated() returns a boolean Series. A row is True if an identical row appeared earlier in the table. Summing it counts the repeats.
import pandas as pd
df = pd.read_csv("train.csv")
print("duplicate rows:", df.duplicated().sum())For the Titanic file this normally prints 0. That result is informative: it means no row is repeated across every column.
Two details are easy to get wrong:
- By default,
duplicated()marks only the second and later copies. The first copy isFalse. Passkeep=Falseto mark every copy, which is useful when you want to look at all of them. - It compares all columns. Rows that differ in even one column are not duplicates.
To check a key column, use subset:
print("repeated PassengerId:", df.duplicated(subset="PassengerId").sum())
print("repeated Name:", df.duplicated(subset="Name").sum())PassengerId should be unique because it identifies each row. If this count is above zero, the file has a problem. A repeated Name is less alarming, since two different people can share a name, but it is worth a look.
If you did find fully identical rows, inspect them first and then drop them:
dupes = df[df.duplicated(keep=False)]
print(dupes)
df = df.drop_duplicates()Do not drop blindly. Identical rows are sometimes legitimate, for example two sales of the same item on the same day.
Looking for implausible values
A value can be present and still be wrong. The checks below use what you know about the real world.
print(df["Age"].min(), df["Age"].max())
print(df["Fare"].min(), df["Fare"].max())
print(df["Survived"].unique())
print(df["Pclass"].unique())Compare each result to what is possible:
| Column | Expected | What a violation looks like |
|---|---|---|
| `Age` | Above 0 and below about 110 | Negative values or ages of 200 |
| `Fare` | 0 or more | Negative fares |
| `Survived` | Only 0 or 1 | Any other code |
| `Pclass` | Only 1, 2, or 3 | A 0 or a 4 |
You can also count violations directly with boolean masks:
bad_age = df[(df["Age"] <= 0) | (df["Age"] > 110)]
print("bad ages:", len(bad_age))
print("zero fares:", (df["Fare"] == 0).sum())Missing ages do not count here. A comparison with NaN evaluates to False, so missing values are silently excluded from these masks.
A zero fare is an example of a value that is possible but suspicious. In the Titanic data, a small number of passengers have Fare equal to 0. This may be crew, guests, or missing data recorded as zero. You cannot settle it from the table alone, so note it as a question instead of deleting the rows.
What to do with what you find
- Exact duplicates: inspect, then drop with
drop_duplicates(). - Impossible values: correct them if the source tells you the right value. Otherwise set them to missing with
df.loc[mask, "Age"] = pd.NA, so they stop affecting averages. - Unusual but possible values: keep them and write down why.
Exercise
A colleague runs df.duplicated().sum() and gets 0. They conclude that no passenger appears twice. Why might that conclusion be wrong, and what check would test it?
Show answer
duplicated() compares every column, so two rows for the same passenger that differ in any column (a typo in Fare, say) are not flagged. Check the identifying column instead with df.duplicated(subset="PassengerId").sum(), and use keep=False to display all rows that share an id.
Exercise
Write code that counts rows where Age is negative or above 110, without counting rows where Age is missing.
Show answer
((df["Age"] < 0) | (df["Age"] > 110)).sum(). Comparisons with NaN return False, so missing ages are not counted.