#1 India's Top IT Training Institute

On Demand Courses

9 programs

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Python Data Cleaning
PDF Downloads

Download the Python data cleaning guide PDF from Uncodemy: missing values, duplicates, types, text and outliers with pandas examples.

Prepared by: Uncodemy trainer team Reviewed by: Uncodemy Last reviewed: 27 Oct 2026
What the Guide Covers
1
Text and duplicatesStandardise labels, drop repeated ids on purpose.
2
Types and datesto_numeric and to_datetime with errors=coerce.
3
Missing valuesDecide per column, fill and flag.
4
OutliersInvestigate before you delete.
5
Reusable functionRules plus assertions that fail loudly.

Quick Answer

This page offers Uncodemy's Python data cleaning guide as a PDF download. It shows how to detect and fix missing values, duplicates, wrong types, messy dates, inconsistent text and outliers using pandas, and how to wrap the steps into a function with checks so that the cleaning is repeatable. The examples build a small messy table in code.

Download

Python Data Cleaning PDF

Download the guide below. Each download is its own file, and everything in it is also explained on this page.

1 PDF Available
PDF 01 Main Guide

Python Data Cleaning

Fixing text, duplicates, types, dates, missing values and outliers with pandas, a reusable cleaning function with assertions, and checks to run after every job, on a small messy customers table.

PDF Free Oct 2026
Download PDF

A short form asks for your details before the download starts. Your details are used only to share study material and course information.

01

Cleaning as code

When data cleaning is written as code rather than done by hand, three good things happen. The steps are documented, because the code is the record of what changed. They are repeatable, because the next file can be cleaned by running the same script. And they are reviewable, because a colleague can read the rules and challenge them.

The price is a little more discipline: you must decide each rule explicitly instead of fixing things as you notice them. The example below uses a small messy customers table so that you can run every step and see the effect.

02

A messy example table

The table has duplicates, inconsistent text, missing values and dates in text form.

import pandas as pd
import numpy as np

raw = pd.DataFrame({
    "customer_id": [1, 2, 2, 3, 4, 5],
    "name": [" Asha ", "ravi", "ravi", "MEERA", None, "Kabir"],
    "city": ["delhi", "Noida ", "Noida ", "NEW DELHI", "Pune", None],
    "signup_date": ["2026-01-05", "05/02/2026", "05/02/2026", "2026-03-10", "bad date", "2026-04-01"],
    "spend": ["500", "1,200", "1,200", None, "300", "-50"],
})

print(raw)
print(raw.isna().sum())
print(raw.duplicated(subset=["customer_id"]).sum(), "duplicate ids")
03

Text and duplicates

Standardise text, map known variants to one label and remove duplicates deliberately, keeping the first row for each id.

df = raw.copy()
df["name"] = df["name"].str.strip().str.title()
df["city"] = (df["city"].str.strip().str.title()
              .replace({"New Delhi": "Delhi"}))
df = df.drop_duplicates(subset=["customer_id"], keep="first")
print(df)
04

Types, dates and numbers

Convert numbers stored as text, parse dates and flag impossible values rather than silently deleting them. errors="coerce" turns failures into missing values, which you can then count.

df["spend"] = pd.to_numeric(df["spend"].str.replace(",", "", regex=False), errors="coerce")
df["signup_date"] = pd.to_datetime(df["signup_date"], errors="coerce", dayfirst=False, format="mixed")
df["spend_invalid"] = df["spend"] < 0
df.loc[df["spend_invalid"], "spend"] = np.nan

print(df.dtypes)
print("unparsed dates:", df["signup_date"].isna().sum())
05

Missing values: decide, then document

After conversion you will have missing values from the original blanks and from values you could not convert. Choose a rule for each column. For a name, a label such as Unknown keeps the row. For spend, the median is a common neutral fill for skewed values, but if the amount drives a calculation you may prefer to leave it missing and report it.

Whatever you do, create a flag column or keep a count, so downstream users know which values were filled. A cleaning step that cannot be seen is a source of mistrust later.

06

Filling and flagging

Fill labels, flag the filled spend values and report how many were affected.

df["name"] = df["name"].fillna("Unknown")
df["city"] = df["city"].fillna("Unknown")
df["spend_was_missing"] = df["spend"].isna()
df["spend"] = df["spend"].fillna(df["spend"].median())

print(df[["customer_id", "name", "city", "spend", "spend_was_missing"]])
print("filled:", int(df["spend_was_missing"].sum()))
07

A reusable cleaning function with checks

Wrap the rules in a function and add assertions, so a bad input fails loudly instead of producing wrong numbers.

def clean_customers(raw):
    df = raw.copy()
    df["name"] = df["name"].str.strip().str.title().fillna("Unknown")
    df["city"] = (df["city"].str.strip().str.title()
                  .replace({"New Delhi": "Delhi"}).fillna("Unknown"))
    df = df.drop_duplicates(subset=["customer_id"], keep="first")
    df["spend"] = pd.to_numeric(df["spend"].str.replace(",", "", regex=False), errors="coerce")
    df.loc[df["spend"] < 0, "spend"] = np.nan
    df["spend"] = df["spend"].fillna(df["spend"].median())

    assert df["customer_id"].is_unique, "ids must be unique"
    assert df["spend"].ge(0).all(), "negative spend remains"
    return df

clean = clean_customers(raw)
print(len(raw), "->", len(clean), "rows")
08

Outliers: what to do

SituationSuggested action
Looks like a typing error (extra zero)Correct from the source or set to missing, with a note
Genuine rare event (a very large order)Keep; report medians or analyse separately
Impossible value (negative age)Mark invalid and investigate
Unknown causeKeep, flag and ask the data owner
09

Good cleaning habits

  • Never overwrite the raw file; read it and write a new cleaned file.
  • Print counts before and after each step.
  • Keep rules in one function or script, in version control.
  • Add tests for the rules that matter, such as unique ids.
  • Write a short log of what changed and why.
10

Common mistakes

  • Dropping rows with any missing value and losing most of the data.
  • Filling with zero when zero means something different from unknown.
  • Parsing dates without checking the day-month order, which swaps values silently.
  • Chained assignment that changes a copy instead of the original.
  • No validation after cleaning.
11

Testing your cleaning code

Cleaning rules deserve tests just like any other code. Create a tiny table that contains the exact problems you expect, such as a duplicate id, a negative amount and a date in the wrong format, run your function on it and assert that the output has the properties you want.

When a new problem appears in real data, add it to the test table first and then fix the code. Over time this builds a safety net, so changes to one rule do not silently break another and so a colleague can trust the function without reading every line.

12

Checks to run after every cleaning job

CheckCode idea
Row count explainedprint(len(raw), len(clean))
Keys uniqueassert clean['customer_id'].is_unique
No impossible valuesassert (clean['spend'] >= 0).all()
Remaining missing valuesprint(clean.isna().sum())
Types as expectedprint(clean.dtypes)

Learn with a trainer

Want to clean and prepare data the way analysts do at work? Explore Uncodemy's Data Analytics course and learn from industry trainers.

View Course
About these PDFs: These PDFs are study material for learning and revision. They are not a certificate, a degree or a promise of a job, and technology changes, so check official documentation for the latest details. Spot an error? Write to info@uncodemy.com and the trainer team will review it.
FAQ

Frequently Asked Questions

How do I clean data in Python?
Use pandas to standardise text, remove duplicates, convert types and dates, handle missing values and outliers with documented rules, and validate the result with checks.
How do I handle missing values in pandas?
Detect them with isna, then drop, fill with a justified value or flag them, depending on the column's meaning. Record what you did.
How do I convert text dates in pandas?
Use pd.to_datetime, with errors set to coerce to expose unparseable values, and check the day-month order carefully.
How do I make cleaning repeatable?
Put the rules in a function or script, add assertions for key checks and keep it under version control.
Should I delete outliers?
Not automatically. Investigate whether they are errors or real events and treat them accordingly.
Are these PDFs free to download?
Yes, the Python data cleaning guide PDF is free. A short form asks for your details before the download starts.