+91 99301 12627
Python & SQL

Data Cleaning in Python: A Step-by-Step Guide with Pandas

By Mehul Prajapati

Cleaning sponge representing data cleaning in Python with Pandas
On this page

Short answer: Data cleaning in Python usually follows these steps with Pandas: (1) inspect the data (info, describe, isna); (2) standardise column names; (3) fix data types such as numbers and dates; (4) handle missing values by dropping, filling or flagging; (5) remove duplicates; (6) clean text (spaces, case, inconsistent categories); (7) treat outliers; and (8) validate the result. Wrap the steps in a reusable function so the same cleaning applies every time new data arrives.

Key takeaways

  • Always inspect before you clean.
  • Decide on missing values using business context, not habit.
  • Keep the raw data unchanged; clean a copy.
  • Make cleaning repeatable with functions or pipelines.

Step 1: Inspect the data

import pandas as pd

raw = pd.read_csv('students.csv')
df = raw.copy()

df.info()
df.describe(include='all')
df.isna().sum().sort_values(ascending=False)
df.duplicated().sum()

Step 2: Standardise column names

df.columns = (df.columns.str.strip().str.lower()
                .str.replace(r'[^a-z0-9]+', '_', regex=True).str.strip('_'))

Step 3: Fix data types

df['fees_paid'] = pd.to_numeric(df['fees_paid'].astype(str).str.replace(',', ''), errors='coerce')
df['joining_date'] = pd.to_datetime(df['joining_date'], dayfirst=True, errors='coerce')
df['batch'] = df['batch'].astype('category')

errors='coerce' turns unparseable values into missing values, so check how many were created.

Step 4: Handle missing values

Approach When to use
Drop rows Few rows missing a critical field (e.g. ID)
Fill with median/mode Numeric or categorical fields with modest missingness
Fill with “Unknown” Categorical fields where missing is meaningful
Add a missing flag When missingness itself may carry information
df = df.dropna(subset=['student_id'])
df['age_missing'] = df['age'].isna()
df['age'] = df['age'].fillna(df['age'].median())
df['city'] = df['city'].fillna('Unknown')

Step 5: Remove duplicates

df = df.sort_values('joining_date').drop_duplicates(subset=['student_id'], keep='last')

Step 6: Clean text and categories

df['city'] = df['city'].str.strip().str.title()
df['city'] = df['city'].replace({'Bombay': 'Mumbai', 'Borivli': 'Borivali'})
df['course'] = df['course'].str.strip().str.lower()

Check categories with df['city'].value_counts() to spot spelling variants.

Step 7: Treat outliers

q1, q3 = df['age'].quantile([0.25, 0.75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
df['age_outlier'] = ~df['age'].between(low, high)

Investigate outliers before removing them: some are errors (age 250), others are real and important.

Step 8: Validate

assert df['student_id'].is_unique
assert df['age'].between(10, 80).all()
assert df['joining_date'].notna().all()

Make it reusable

def clean_students(raw: pd.DataFrame) -> pd.DataFrame:
    df = raw.copy()
    # ...apply steps 2-7...
    return df

clean = clean_students(pd.read_csv('students.csv'))

For tabular ML, put imputation and encoding inside a scikit-learn Pipeline to avoid leakage. See feature engineering.

Common mistakes

  • Overwriting the raw data
  • Filling every missing value with 0
  • Dropping outliers without checking them
  • Cleaning differently each time by hand
  • Ignoring date formats (DD/MM vs MM/DD)

Frequently asked questions

How much time does data cleaning take?

Often a large share of an analysis project, which is why reusable cleaning code is so valuable.

Should I clean data in SQL or Python?

Both are common: SQL for filtering and joining at the source, Python for complex transformations. See SQL for data science.

Is data cleaning asked in interviews?

Yes, often as a practical task. Practise with Pandas interview questions.

Conclusion

Data cleaning in Python is a repeatable process: inspect, standardise, fix types, handle missing values and duplicates, clean text, treat outliers and validate. Write it once as a function and every future analysis starts from trustworthy data.

Practise data cleaning on real datasets in our Python course.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.