Menu

Cleaning and Transforming Data

Lesson 4: Cleaning and Transforming Data

Why clean data?

Real datasets commonly contain:

  • Missing values – blank cells, NaN, None
  • Duplicates – the same record entered twice
  • Inconsistent labels – 'south', 'South ', 'SOUTH'
  • Incorrect types – dates or numbers stored as text
  • Invalid values – negative quantities, impossible dates

Cleaning makes analysis more dependable, but every change should follow a clear, documented rule, not a guess.

Example

# 1. Remove exact duplicate rows
df = df.drop_duplicates()
# 2. Standardise text labels
df['region'] = df['region'].str.strip().str.title()
# 3. Convert dates; invalid values become NaT (missing)
df['order_date'] = pd.to_datetime(df['order_date'], errors='coerce')
# 4. Convert currency text to numbers
df['amount'] = pd.to_numeric(
df['amount'].astype(str).str.replace('[₹,]', '', regex=True),
errors='coerce'
)

How it works

Step

Method

Effect

Remove duplicatesdrop_duplicates()Removes exact duplicate rows by default; use subset=['order_id'] to check specific columns
Trim spaces.str.strip()' South ' → 'South'
Fix case.str.title() / .str.lower()'SOUTH' → 'South'
Replace labels.replace({'TN': 'Tamil Nadu'})Maps known variations
Parse datespd.to_datetime(..., errors='coerce')Valid dates converted; invalid → NaT
Parse numberspd.to_numeric(..., errors='coerce')Valid numbers converted; invalid → NaN
Change type.astype('category') / .astype(str)Sets an explicit type
Rename columnsdf.rename(columns={'Amt': 'amount'})Consistent names

Missing values

Step 1 – Measure:

df.isna().sum() # missing count per column
df.isna().mean().round(3) * 100 # missing percentage per column

Step 2 – Look for patterns: Is missingness concentrated in one region, month, or device?

Step 3 – Choose a treatment:

Option

Code

When it's appropriate

Keep as missing–The field isn't needed for this analysis
Exclude from a calculationdf['x'].mean() (pandas skips NaN by default)Missing is a small, random share
Drop rowsdf.dropna(subset=['amount'])The value is essential and missing rows are few
Fill with a ruledf['x'].fillna(df['x'].median())A defensible rule exists
Fill a categorydf['region'].fillna('Unknown')Keeps rows while labelling the gap
Fix at source–Ask the data owner

Do not automatically replace every missing number with zero. A missing price is not a free product.

Common mistakes

  • Overwriting the original data: keep the raw file unchanged; save a cleaned copy.
  • Not documenting decisions: note what you changed and why.
  • Not counting affected rows: compare len(df) before and after each step.
  • Over-aggressive cleaning: a rule based on a wrong assumption can delete legitimate records.
  • Chained assignment warnings: use df.loc[condition, 'col'] = value instead of df[condition]['col'] = value.

Try it: Inspect a dataset for missing values and duplicates. Standardise one category column and report how many values changed.


Data Analytics Tutorial



Learn via Video Course

Data Analysis and Processing with Python using Pandas - Data Science Course Logo

Data Analysis and Processing with Python using Pandas - Data Science Course

5 hrs



Get in Touch For Details