Sub topic 2
Checking for Duplicate Rows and Implausible Values
Assume you know basic Python and can run a notebook or script. The examples use pandas and the Titanic train.csv file loaded into a DataFrame named df.
Checking for Duplicate Rows and Implausible Values
A duplicate row repeats the same values across every column. Check duplicates before summarizing data, because repeated records can make counts and averages misleading.
import pandas as pd
df = pd.read_csv("train.csv")
print("duplicate rows:", df.duplicated().sum())
print(df[df.duplicated(keep=False)].sort_values("Name").head())
print(df[["Age", "Fare", "SibSp", "Parch"]].describe())
print("invalid ages:", ((df["Age"] < 0) | (df["Age"] > 120)).sum())
print("invalid fares:", (df["Fare"] < 0).sum())Use domain knowledge to decide whether a value is implausible. An empty Age is missing, not automatically invalid. A negative fare is invalid. A very high fare may be unusual but still possible.
Summarizing Numeric Columns
describe() gives count, mean, standard deviation, minimum, quartiles, and maximum for numeric columns. Compare count with the total row count to notice missing values.
| Statistic | What it helps reveal |
|---|---|
| `min` and `max` | Possible range errors or outliers |
| `mean` and quartiles | Typical values and skew |
| `count` | How many non-missing values exist |
Counting Categories
For text or categorical columns, value_counts() shows frequency. Include missing values with dropna=False.
print(df["Sex"].value_counts(dropna=False))
print(df["Embarked"].value_counts(dropna=False))
print(df["Pclass"].value_counts(dropna=False))Selecting Columns and Filtering Rows
Use a boolean mask to keep rows matching a condition. Put each condition in parentheses when combining masks with &.
women_first = df.loc[
(df["Sex"] == "female") & (df["Pclass"] == 1),
["Name", "Age", "Fare", "Survived"],
]
print(women_first.head())Adding Derived Columns Such as Age Groups
A derived column stores a useful transformation while preserving the raw column. pd.cut() places numeric values into labeled intervals. Missing ages remain missing.
df["AgeGroup"] = pd.cut(
df["Age"],
bins=[0, 12, 18, 40, 60, 120],
labels=["child", "teen", "adult", "middle_aged", "senior"],
)
print(df["AgeGroup"].value_counts(dropna=False))Exercise
Why should you inspect the number of missing ages before interpreting the age-group counts?
Show answer
Missing ages do not enter an age group, so the group counts may exclude part of the dataset and may not represent all passengers.