Menu

Data Cleaning Basics

Data Cleaning Basics

Raw data is almost never ready to use. Cleaning fixes errors and gaps so that your analysis and models can be trusted. This topic covers the most common cleaning tasks every beginner should know.

Handling Missing Values

Missing values appear as NaN in Pandas. You can handle them in two main ways: remove them or fill them. The right choice depends on how much data is missing and why.

If only a few rows have missing values, dropping them is simple. If many are missing, filling is better so you do not lose too much information. You can fill with the mean, median, most common value, or a fixed label.

df = df.dropna(subset=["customer_id"])
df["age"] = df["age"].fillna(df["age"].median())

The median is often safer than the mean when data has extreme values. Always think about what a missing value really means before filling it.

Removing Duplicates

Duplicate rows happen when the same record is entered more than once or when files are combined. They can inflate counts and totals and make your results wrong.

print(df.duplicated().sum())
df = df.drop_duplicates()

You can also check duplicates based on certain columns, such as email or order ID. Use the subset option for this. Be careful to remove only true duplicates.

Two different customers may share the same name, so never rely on a single weak column. Choose columns that truly identify a unique record.

Fixing Data Types and Inconsistent Values

Columns often have the wrong type. A price stored as text cannot be used for math, and a date stored as text cannot be used for time analysis. Convert them with astype(), to_numeric(), or to_datetime().

df["price"] = pd.to_numeric(df["price"], errors="coerce")
df["date"] = pd.to_datetime(df["date"])

Text values can also be inconsistent. "Delhi", "delhi", and "Delhi " all mean the same city but look different to a computer. Clean them using string methods like str.strip(), str.lower(), and str.title().

Use value_counts() after cleaning to confirm that each category now appears only once. Consistent values make grouping and counting correct.

Documenting Your Cleaning Steps

Every change you make to the data should be written down. This is called documentation, and it is a key habit of good data scientists. It lets others understand and repeat your work.

Keep a simple log. Note what problem you found, what you did to fix it, and why. You can write this as comments in your code or as notes in a Jupyter notebook.

Also keep a copy of the original data. Never overwrite it. Work on a copy so you can always go back if you make a mistake or if someone questions a decision.


Data Science Lifecycle Tutorial

WR

Wesline Rinisha



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details