Python

Data Cleaning with pandas: 10 Techniques I Use on Every Project

A tested pandas cleaning workflow: tidy columns, parse 'Rs. 1,25,000' safely, normalise Nepali phone numbers and dates, dedupe and validate.

Key takeaways

  • Data cleaning is usually most of the work in a data or ML project — and the part that decides whether results can be trusted.
  • Clean in a fixed order: column names → text → numbers → dates → duplicates → missing values → validation.
  • Never trust a conversion you haven't checked. One stray character can turn Rs 1,25,000 into 0.125 without any error.

Every dataset I've received at work — bank reports, school records, survey exports, Excel files from five different departments — has needed cleaning before anything useful could happen. Tutorials tend to start with tidy CSVs. Real files have trailing spaces, three spellings of "Kathmandu", amounts written as text and dates in two formats in the same column.

This guide walks through the cleaning routine I use on almost every project, with code you can copy. Every snippet below was run with pandas 3, and the outputs shown are real.

The messy example dataset

Here's a small file that contains most of the problems I see in practice:

import io
import numpy as np
import pandas as pd

raw = io.StringIO("""Customer Name ,Phone,City,Amount,Txn Date,Status
 Ram Sharma,+977-9801234567,Kathmandu,"Rs. 1,25,000",2026-01-15,Success
sita thapa,9812345678,kathmandu ,"12,500",15/01/2026,success
Ram Sharma,+977-9801234567,Kathmandu,"Rs. 1,25,000",2026-01-15,Success
Hari K.C.,01-4412345,Lalitpur,N/A,2026-01-17,FAILED
Gita Rai,980-123-9999,Bhaktapur,4500,,Pending
""")
df = pd.read_csv(raw)

Spot the issues: a column name with a trailing space, inconsistent capitalisation, amounts with a currency prefix and Nepali-style digit grouping, phone numbers in four formats, a landline where a mobile is expected, two date formats, a missing date, and a duplicated row.

1. Standardise column names

Consistent, lower-case, underscore-separated names save you from KeyErrors for the rest of the project.

df.columns = (df.columns.str.strip()
                        .str.lower()
                        .str.replace(r"[^a-z0-9]+", "_", regex=True)
                        .str.strip("_"))
print(df.columns.tolist())
# ['customer_name', 'phone', 'city', 'amount', 'txn_date', 'status']

2. Strip whitespace from every text column

Leading and trailing spaces are invisible in Excel but make "Kathmandu" and "Kathmandu " different values.

text_cols = df.select_dtypes(include=["object", "string"]).columns
df[text_cols] = df[text_cols].apply(lambda s: s.str.strip())

Including both "object" and "string" keeps the code working on pandas 2 and pandas 3, which changed the default dtype for text.

3. Normalise categories

Decide on one canonical form for each categorical column and apply it everywhere.

df["city"] = df["city"].str.title()            # kathmandu -> Kathmandu
df["status"] = df["status"].str.lower()        # Success / FAILED -> success / failed
df["customer_name"] = df["customer_name"].str.title()

For messier categories (for example "Ktm", "Kathmandu", "KTM Valley"), build an explicit mapping dictionary and apply it with .replace(). Then check df["city"].value_counts() to catch anything you missed.

4. Convert currency text to numbers — carefully

This is where silent bugs live. A tempting one-liner is to delete everything except digits and dots:

# DON'T do this
df["amount"].str.replace(r"[^0-9.]", "", regex=True)
# "Rs. 1,25,000" -> ".125000" -> 0.125   (the dot from "Rs." survives!)

This is an easy mistake to make, and it turns one lakh twenty-five thousand rupees into 0.125 with no error or warning. Remove the currency prefix explicitly first, then the thousands separators:

amount = (df["amount"].str.replace(r"(?i)^(rs|npr)\.?\s*", "", regex=True)
                      .str.replace(",", "", regex=False))
df["amount"] = pd.to_numeric(amount, errors="coerce")
print(df["amount"].tolist())
# [125000.0, 12500.0, 125000.0, nan, 4500.0]

errors="coerce" turns anything unparseable (like "N/A") into NaN instead of crashing. That's convenient, but it can also hide problems — always count how many values became NaN after a conversion and look at a few of them.

Lakh-style grouping

Nepal and India group digits as 1,25,000 (lakh) rather than 125,000. Removing all commas handles both styles. Just make sure no column uses commas as decimal separators, as some European exports do.

5. Normalise phone numbers

Nepali mobile numbers are 10 digits starting with 9. Numbers arrive with country codes, dashes and spaces. A small function makes them consistent and rejects anything that isn't a valid mobile:

def normalize_np_mobile(x):
    if pd.isna(x):
        return np.nan
    digits = "".join(ch for ch in str(x) if ch.isdigit())
    if digits.startswith("977"):
        digits = digits[3:]
    return digits if len(digits) == 10 and digits.startswith("9") else np.nan

df["mobile"] = df["phone"].map(normalize_np_mobile)
print(df["mobile"].tolist())
# ['9801234567', '9812345678', '9801234567', nan, '9801239999']

The Lalitpur landline (01-4412345) correctly becomes NaN in the mobile column. We keep the original phone column so no information is lost.

6. Parse dates in mixed formats

df["txn_date"] = pd.to_datetime(df["txn_date"], format="mixed", dayfirst=True, errors="coerce")
print(df["txn_date"].tolist())
# [Timestamp('2026-01-15'), Timestamp('2026-01-15'), Timestamp('2026-01-15'),
#  Timestamp('2026-01-17'), NaT]

dayfirst=True matters: in Nepal, 05/01/2026 usually means 5 January, not May 1. If your source mixes conventions, there's no safe automatic answer — find out from whoever produced the file.

Bikram Sambat dates

Many Nepali systems store dates in Bikram Sambat (BS), such as 2082-10-01. pandas doesn't understand BS directly. Convert BS to Gregorian (AD) using a dedicated library such as nepali-datetime before analysis, and keep the original BS column for reporting.

7. Remove duplicates

before = len(df)
df = df.drop_duplicates()
print(before, len(df))   # 5 4

Run deduplication after cleaning text and numbers; otherwise " Ram Sharma" and "Ram Sharma" look different and the duplicate survives. For real data, decide what makes a record unique (for example, a transaction ID) and use drop_duplicates(subset=[...]).

8. Decide how to handle missing values

print(df.isna().sum().to_dict())
# {'customer_name': 0, 'phone': 0, 'city': 0, 'amount': 1, 'txn_date': 1, 'status': 0, 'mobile': 1}

There's no universal rule. Ask why a value is missing. A missing amount on a failed transaction may be correct; a missing date on a pending transaction may just mean "not yet". Options are to leave it (and handle it in analysis), fill it (median, a default, or a value from another source), or drop the row — and the choice should be documented. For machine learning, do any filling inside a scikit-learn pipeline to avoid leakage, as shown in my CKD case study.

9. Derive the columns you need

df["day"] = df["txn_date"].dt.day_name()
summary = (df[df["status"] == "success"]
             .groupby("city", as_index=False)
             .agg(transactions=("amount", "size"), total=("amount", "sum")))
print(summary)
#         city  transactions     total
# 0  Kathmandu             2  137500.0

10. Validate with assertions

Finish with checks that fail loudly if your assumptions are wrong. When next month's file arrives in a different format, you'll find out immediately instead of after the report has gone to your manager.

assert df["amount"].dropna().ge(0).all(), "negative amounts found"
assert df["mobile"].dropna().str.len().eq(10).all(), "bad mobile numbers"
assert df["status"].isin(["success", "failed", "pending"]).all(), "unknown status"

Turn it into a reusable function

Once the steps work, wrap them in a function (or a small module) and run it on every new file. A repeatable cleaning script is the foundation of any automation: the same code can run every morning inside a scheduled job or an n8n workflow — see no-code automation tools for ideas.

Checklist

  1. Standardise column names.
  2. Strip whitespace in text columns.
  3. Normalise categories and check value_counts().
  4. Convert numbers explicitly; count new NaNs.
  5. Normalise identifiers like phone numbers.
  6. Parse dates with the correct day/month order.
  7. Deduplicate after cleaning.
  8. Handle missing values deliberately and document the choice.
  9. Derive analysis columns.
  10. Validate with assertions.

Spotted an error or have a question about this article? Send me a message — corrections are applied and noted with an updated date. See the editorial policy.

Keep reading

More articles you may find useful.

All articles