Sub topic 2
Auditing and Exploring Data
Assume you know basic Python, pandas DataFrames, Jupyter, and introductory statistics. This chapter treats the notebook as a repeatable investigation, not a scratchpad.
Audit Before Cleaning
Start by measuring problems before changing the data. Check missing values, duplicate rows, data types, and values outside the domain you expect.
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())
print(df_raw.describe(include="all").T)For example, an order amount below zero is usually implausible. A missing region may need a separate category, removal, or investigation. Choose the response based on the meaning of the field, not on convenience.
Clean with Named Steps
Put cleaning rules in a function. The function should return a new DataFrame, so you can run it again after changing the rules.
def clean_orders(df):
out = df.drop_duplicates().copy()
out["region"] = out["region"].str.strip().str.lower()
out = out[out["amount"].notna() & (out["amount"] >= 0)]
return out
df = clean_orders(df_raw)
print(f"rows kept: {len(df)} of {len(df_raw)}")A named function makes decisions visible and testable. Keep a count of removed rows and document unusual choices in a nearby markdown cell.
Make Plots Readable
Every plot needs a title, labeled axes, and units where relevant. A reader should understand the chart without guessing what each axis means.
Examine One Variable
Univariate analysis examines one variable at a time. Use a histogram for a numeric distribution and summary statistics for its center and spread.
ax = df["amount"].plot.hist(bins=30)
ax.set_title("Order amount distribution")
ax.set_xlabel("Amount")
ax.set_ylabel("Number of orders")Compare the mean and median. A large gap can indicate skew or outliers. Record the observation, evidence, hypothesis, and next question beside the plot.
Exercise
Why should cleaning happen in a function instead of in scattered notebook cells?
Show answer
A function makes each rule explicit, repeatable, and easier to inspect or revise.