Lesson 12 of 23
โฎPrev Nextโฏ

PY-401 ยท Cleaning messy data

Fixing types and dates

โฑ 9 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

12of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    A column often loads as text (object) even when it holds numbers or dates. pd.to_numeric(col, errors="coerce") turns text into numbers and bad values into NaN, pd.to_datetime(col) turns text into real dates, and col.astype(int) changes a clean column's type. Once a column is a date, .dt gives you the day, month or weekday.

    • Spot wrong types with dtypes
    • Convert text to numbers and dates
    • Read parts of a date with .dt

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Fixing types and dates, running
    1. import pandas as pd
    2. orders = pd.DataFrame({
    3. "order_date": ["2026-03-01", "2026-03-04", "2026-03-09"],
    4. "amount": ["1,200", "350", "n/a"],
    5. "qty": ["3", "1", "2"],
    6. })
    7. print(orders.dtypes)
    8. orders["order_date"] = pd.to_datetime(orders["order_date"])
    9. orders["amount"] = pd.to_numeric(orders["amount"].str.replace(",", ""), errors="coerce")
    10. orders["qty"] = orders["qty"].astype(int)
    11. print(orders.dtypes)
    12. print(orders["order_date"].dt.day_name().tolist())
    13. print(orders["amount"].sum())
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemFinance asks for the March total. You run sum() on the amount column and get "1,200350n/a", because the numbers are text with commas and a "n/a" in the middle.
    2. The Python ideapd.to_numeric(df["col"], errors="coerce")A column often loads as text (object) even when it holds numbers or dates.
    3. In real lifeAn e-commerce team converts order timestamps with to_datetime and then groups by dt.hour to find out that most orders arrive between 8 and 10 in the evening, so that is when they run promotions.

    Start with a question

    Finance asks for the March total. You run sum() on the amount column and get "1,200350n/a", because the numbers are text with commas and a "n/a" in the middle.

    Sums, averages, sorting by date and grouping by month all need the right types. Wrong types are the most common reason an analysis gives nonsense.

    Explain it like I'm 10

    A price written on paper is just ink. You have to read it as a number before you can add it up. Converting types is pandas reading the ink properly.

    The technical explanation

    df.dtypes shows each column's type. object usually means text.

    Clean text first if needed, for example .str.replace(",", "") to remove thousands separators, then pd.to_numeric(..., errors="coerce").

    pd.to_datetime(col) understands ISO dates like 2026-03-01. For other formats pass format="%d/%m/%Y" so 03/04 is read the way you mean.

    col.astype(int) works when every value is already a clean whole number. After conversion, col.dt.day_name(), col.dt.month and col.dt.year read parts of a date.

    Syntax

    pd.to_numeric(df["col"], errors="coerce")
    pd.to_datetime(df["col"], format="%Y-%m-%d")
    df["col"].astype(int)
    df["date"].dt.month

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    An e-commerce team converts order timestamps with to_datetime and then groups by dt.hour to find out that most orders arrive between 8 and 10 in the evening, so that is when they run promotions.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. A numbers column shows dtype object. What does that usually mean?
    2. 2. What does errors="coerce" do?
    3. 3. Which turns "2026-03-01" text into a real date?
    4. 4. After conversion, how do you get the month number?
    5. 5. Why remove "," before converting "1,200"?

    Questions people ask

    How do I convert a column to numbers in pandas?

    Use pd.to_numeric(df["col"], errors="coerce"). Clean symbols such as commas or currency signs first with .str.replace, because those make values unreadable and they become NaN.

    How do I read dates like 03/04/2026 correctly in pandas?

    Pass the format so pandas does not guess: pd.to_datetime(df["date"], format="%d/%m/%Y") for day first, or "%m/%d/%Y" for month first.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner How do I convert a column to numbers in pandas?

    Use pd.to_numeric(df["col"], errors="coerce"). Clean symbols such as commas or currency signs first with .str.replace, because those make values unreadable and they become NaN.

    beginner How do I read dates like 03/04/2026 correctly in pandas?

    Pass the format so pandas does not guess: pd.to_datetime(df["date"], format="%d/%m/%Y") for day first, or "%m/%d/%Y" for month first.

    intermediate A numbers column shows dtype object. What does that usually mean?

    The values are stored as text. object usually means strings, so maths will not work properly.

    intermediate What does errors="coerce" do?

    Turns values it cannot convert into NaN. Bad values become missing instead of stopping the conversion.

    Quick revision

    Remember

    • Spot wrong types with dtypes
    • Convert text to numbers and dates
    • Read parts of a date with .dt
    • Use errors="coerce" with to_numeric and to_datetime. Without it, one bad value like "n/a" stops the whole conversion with an error.

    Syntax

    pd.to_numeric(df["col"], errors="coerce")
    pd.to_datetime(df["col"], format="%Y-%m-%d")
    df["col"].astype(int)
    df["date"].dt.month

    Official documentation