Python Central HubSign in

Data Analytics with Python / Phase 4: Data Preprocessing and Cleaning

Data Type Conversion and Validation

Convert columns safely to numeric/datetime/category and validate schema assumptions.

Why dtype conversion matters

Many datasets arrive with wrong dtypes:

  • numbers stored as strings
  • dates stored as strings
  • categories stored inconsistently

If dtypes are wrong, your stats and charts can be wrong.

Convert to numeric safely

Python
import pandas as pd
 
df = pd.DataFrame({"amount": ["1,200", "500", "oops", " 700 "]})
 
df["amount"] = df["amount"].astype(str).str.replace(",", "", regex=False).str.strip()
df["amount"] = pd.to_numeric(df["amount"], errors="coerce")
 
print(df)
print(df.isna().sum())

Convert to datetime

Python
import pandas as pd
 
df = pd.DataFrame({"date": ["2025-01-01", "2025/01/02", "invalid"]})
 
df["date"] = pd.to_datetime(df["date"], errors="coerce")
print(df)

Categories

Python
import pandas as pd
 
df = pd.DataFrame({"city": ["Pune", "Delhi", "Pune"]})
 
df["city"] = df["city"].astype("category")
print(df.dtypes)

Validate assumptions

Typical checks:

  • ID columns contain no duplicates
  • numeric columns are non-negative
  • date columns are within expected range
Python
# no duplicate ids
# assert df["id"].is_unique
 
# non-negative values
# assert (df["amount"] >= 0).all()
 
# date range
# assert df["date"].min() >= pd.Timestamp("2020-01-01")

Tip

Convert + validate early. It prevents subtle bugs later.

Visualize it

Each column starts life as text (or a mixed bag of types) and needs to be routed to the right converter before it's safe to use.

diagram Dtype conversion flow mermaid
Raw string columns are routed to a numeric, datetime, or category converter, with unparseable values becoming NA.

๐Ÿงช Try It Yourself

Exercise 1 โ€“ Convert text to numbers safely

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 2 โ€“ Convert a column to category

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Exercise 3 โ€“ Use a nullable integer dtype

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Check your understanding

quizCheck yourself
  1. For amounts "1,200", "500", "oops" and " 700 ", how many NaN values result after cleaning and to_numeric(errors="coerce")?

    Show answer

    A โ€” 1 โ€” The commas and spaces are removed so 1,200 and 700 convert fine. Only oops cannot be parsed and becomes NaN.

  2. Which line checks that an ID column has no duplicates?

    Show answer

    A โ€” assert df["id"].is_unique โ€” is_unique is True when no value repeats. The lesson also checks non-negative amounts and date ranges.

  3. Which call converts a text column of repeated cities to a categorical dtype?

    Show answer

    A โ€” df["city"].astype("category") โ€” astype("category") makes the column categorical, as the dtypes printout shows.

  4. Why does the lesson say to convert and validate early?

    Show answer

    A โ€” Wrong dtypes make stats and charts wrong, and early checks prevent subtle bugs โ€” If dtypes are wrong, your numbers and plots can be wrong without warning.

Next

With clean dtypes in hand, you're ready to hunt for extreme values โ€” see Outlier Detection (IQR Method) and Handling Outliers.

Was this page helpful?

Let us know how we did