Skip to main content
Albero Academy

Cleaning & Transforming

Handle missing data, fix dtypes, rename and map values, and create new columns — the real work of any analysis.

Chapter 3Pandas16 min readBeginner friendly
  • #Pandas
  • #Cleaning
  • #Missing Data

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:

missing values
df.isna().sum() # count NaNs per column — always start here
df.dropna() # drop any row with a NaN
df.dropna(subset=["email"]) # only where email is missing
df["package"].fillna(0) # fill with a constant
df["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:

type conversion
df["package"] = pd.to_numeric(df["package"], errors="coerce") # bad → NaN
df["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):

new columns
# Vectorised — the fast way
df["package_inr"] = df["package"] * 100000
# String methods
df["name_upper"] = df["name"].str.upper()
# Conditional column with np.where
import numpy as np
df["tier"] = np.where(df["package"] >= 7, "high", "standard")
# apply — arbitrary Python per row when vectorising isn't possible
df["label"] = df["package"].apply(lambda p: "distinction" if p >= 7.5 else "pass")

Renaming & mapping

rename & map
df = df.rename(columns={"package": "package_lpa"})
# Replace values via a mapping
df["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

  1. 01Missing values are NaN — start with df.isna().sum(), then dropna or fillna deliberately.
  2. 02Fix dtypes explicitly: to_numeric (errors="coerce"), to_datetime, astype("category").
  3. 03After to_datetime, the .dt accessor exposes year/month/day and more.
  4. 04Create columns with vectorised maths/string methods or np.where; use apply only when needed.
  5. 05rename, map, replace and drop reshape a messy table into a tidy one.