#1 India's Top IT Training Institute
×

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 →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

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 →

Data Cleaning Techniques Every Analyst Should Know

Data cleaning is the work of turning raw data into something you can trust: removing duplicates, fixing types and formats, deciding what to do with missing values and flagging suspicious numbers. The core techniques are few, and they are the same in pandas, Excel and SQL. Below, each one is applied to the same small orders table so you can see exactly what changes.

Data Cleaning Analyst

Data Cleaning Techniques Every Analyst Should Know

The messy table

Here is a typical export from an order system, small enough to read at a glance:

import pandas as pd

df = pd.DataFrame({
    "order_id":   [101, 102, 102, 103, 104, 105, 106],
    "city":       ["Bengaluru", " bangalore", " bangalore", "Pune", "PUNE ", "Delhi", None],
    "order_date": ["2026-03-01", "01/03/2026", "01/03/2026", "2026-03-02", "2026-03-02", "2026-03-03", "2026-03-03"],
    "amount":     ["1,250", "899", "899", "Rs 2,100", "450", "98000", "620"],
})
print(df)
   order_id        city  order_date    amount
0       101   Bengaluru  2026-03-01     1,250
1       102   bangalore  01/03/2026       899
2       102   bangalore  01/03/2026       899
3       103        Pune  2026-03-02  Rs 2,100
4       104       PUNE   2026-03-02       450
5       105       Delhi  2026-03-03     98000
6       106         NaN  2026-03-03       620

Count the problems: a duplicated order, three spellings of two cities, two date formats, amounts stored as text with commas and a prefix, one missing city and one amount that looks far too large. Real exports have all of these, usually at once.

Technique 1: remove exact duplicates

print("duplicate rows:", df.duplicated().sum())
df = df.drop_duplicates()
duplicate rows: 1

Row 2 is identical to row 1, so it goes. Be careful with "near duplicates" such as the same order with a different timestamp; for those, decide which columns define a unique record (here order_id) and use drop_duplicates(subset=["order_id"], keep="last") only after you understand why the copies exist.

Technique 2: standardise text

df["city"] = df["city"].str.strip().str.title()
df["city"] = df["city"].replace({"Bangalore": "Bengaluru"})

strip() removes the leading and trailing spaces, title() fixes the case, and a mapping merges old and new names. Without this, a group-by on city would report Pune and "PUNE " as two different cities. Keep the mapping in one place (a small CSV or dictionary) so the whole team uses the same spellings.

Technique 3: fix numbers stored as text

df["amount"] = (df["amount"].str.replace("Rs", "", regex=False)
                             .str.replace(",", "", regex=False)
                             .str.strip()
                             .astype(int))

Text amounts sort wrongly ("98000" comes before "999" alphabetically) and cannot be summed. Remove currency labels and thousands separators, then convert. If some values cannot convert, pd.to_numeric(..., errors="coerce") turns them into missing values you can inspect instead of crashing.

Technique 4: parse mixed date formats explicitly

iso = pd.to_datetime(df["order_date"], format="%Y-%m-%d", errors="coerce")
dmy = pd.to_datetime(df["order_date"], format="%d/%m/%Y", errors="coerce")
df["order_date"] = iso.fillna(dmy)

Each format is parsed separately and the results combined. Letting the library guess is risky with Indian data: "01/03/2026" means 1 March in DD/MM order but 3 January in US MM/DD order. Always state the format you expect.

Technique 5: handle missing values on purpose

print(df.isna().sum())
df["city"] = df["city"].fillna("Unknown")
order_id      0
city          1
order_date    0
amount        0
dtype: int64

You have four honest choices: leave it missing, fill it with a label such as "Unknown", fill it from another source (the customer's address table), or drop the row. Filling numbers with the mean is common in tutorials but can distort totals and averages; only do it when you can explain why it is reasonable. Whatever you choose, write it down.

Technique 6: flag outliers instead of deleting them

q1, q3 = df["amount"].quantile([0.25, 0.75])
iqr = q3 - q1
high = q3 + 1.5 * iqr
print("q1, q3, upper fence:", q1, q3, high)
df["amount_flag"] = df["amount"] > high
q1, q3, upper fence: 689.75 1887.5 3684.125

The interquartile-range (IQR) rule marks anything above Q3 + 1.5 × IQR as unusual. Order 105 at 98,000 is flagged. It might be a typing error (an extra zero) or a genuine bulk order. Check with the business before removing it; an outlier is a question, not automatically a mistake.

Technique 7: validate the result

After cleaning, the table looks like this:

   order_id       city order_date  amount  amount_flag
0       101  Bengaluru 2026-03-01    1250        False
1       102  Bengaluru 2026-03-01     899        False
3       103       Pune 2026-03-02    2100        False
4       104       Pune 2026-03-02     450        False
5       105      Delhi 2026-03-03   98000         True
6       106    Unknown 2026-03-03     620        False

Then run quick checks you can automate:

assert df["order_id"].is_unique
assert df["amount"].ge(0).all()
assert df["order_date"].notna().all()
assert set(df["city"]) <= {"Bengaluru", "Pune", "Delhi", "Unknown"}

If any assertion fails next week, when a new export arrives, you find out immediately instead of in a wrong report. Output above was produced with pandas 3.1; older versions print the same values.

The same techniques in Excel and SQL

TechniquepandasExcelSQL
Remove duplicatesdrop_duplicates()Data → Remove DuplicatesROW_NUMBER() OVER (PARTITION BY order_id ...), keep row 1
Standardise textstr.strip(), str.title(), replace()TRIM, PROPER, a lookup table with XLOOKUPTRIM, LOWER/UPPER, CASE or a mapping table
Text to numberstr.replace() then astype(int)SUBSTITUTE then VALUEREPLACE then CAST(... AS INT)
Parse datesto_datetime(format=...)DATE with LEFT/MID/RIGHT, or Text to ColumnsSTR_TO_DATE (MySQL), TO_DATE (PostgreSQL)
Missing valuesisna(), fillna()Filter blanks, IF(ISBLANK(...))COALESCE, WHERE col IS NULL
Outliersquantile() and the IQR ruleQUARTILE.INCPERCENTILE_CONT (PostgreSQL)

Power Query in Excel and Power BI can record most of these steps so they repeat automatically on the next file.

Habits that matter more than any function

  • Never edit the raw file. Keep it untouched and clean a copy, in code or in Power Query, so every step can be repeated.
  • Log every decision. "Filled 1 missing city with Unknown; flagged 1 order above 3,684" belongs in your notes or notebook.
  • Clean with the business question in mind. A column you will not use does not need perfect cleaning today.
  • Re-check counts after each step. Row counts that drop unexpectedly usually mean a filter or join went wrong.

To practise the pandas side further, see pandas for data manipulation. If most of your work is in spreadsheets, Excel functions for data analysts covers the formulas above in more depth, and SQL joins in real projects explains the join mistakes that create duplicates in the first place.

Placed Students

Our Clients

Partners

...