Cleaning is where analysts spend most of their time — and where results are won or lost. This chapter covers the recurring jobs: dealing with missing values, correcting types, and deriving new columns from existing ones.
Missing data
Pandas marks missing values as NaN. First find them, then decide to drop or fill — never ignore them, since they silently break sums and averages:
df.isna().sum() # count NaNs per column — always start heredf.dropna() # drop any row with a NaNdf.dropna(subset=["email"]) # only where email is missingdf["package"].fillna(0) # fill with a constantdf["package"].fillna(df["package"].median()) # fill with the median
Fixing dtypes
Numbers read as text and dates read as strings are the two most common data bugs. Fix them explicitly:
df["package"] = pd.to_numeric(df["package"], errors="coerce") # bad → NaNdf["enrolled"] = pd.to_datetime(df["enrolled"])df["programme"] = df["programme"].astype("category") # saves memory# Now date parts are available:df["year"] = df["enrolled"].dt.year
Transforming columns
Derive new columns with vectorised operations (fast, preferred) or apply for custom logic (flexible, slower):
# Vectorised — the fast waydf["package_inr"] = df["package"] * 100000# String methodsdf["name_upper"] = df["name"].str.upper()# Conditional column with np.whereimport numpy as npdf["tier"] = np.where(df["package"] >= 7, "high", "standard")# apply — arbitrary Python per row when vectorising isn't possibledf["label"] = df["package"].apply(lambda p: "distinction" if p >= 7.5 else "pass")
Renaming & mapping
df = df.rename(columns={"package": "package_lpa"})# Replace values via a mappingdf["programme"] = df["programme"].map({"Data": "Data Analytics","Full Stack": "Full Stack Development",})df["status"] = df["status"].replace("pend", "pending")df = df.drop(columns=["temp_col"])
Practice
On your dataset: count missing values per column, fill or drop them with a justified choice, convert a text column that should be numeric with to_numeric, parse a date column, and add a derived column using np.where.
Key takeaways
- 01Missing values are NaN — start with df.isna().sum(), then dropna or fillna deliberately.
- 02Fix dtypes explicitly: to_numeric (errors="coerce"), to_datetime, astype("category").
- 03After to_datetime, the .dt accessor exposes year/month/day and more.
- 04Create columns with vectorised maths/string methods or np.where; use apply only when needed.
- 05rename, map, replace and drop reshape a messy table into a tidy one.
