PY-401 ยท Cleaning messy data
Fixing types and dates
โฑ 9 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก 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.
import pandas as pdorders = pd.DataFrame({"order_date": ["2026-03-01", "2026-03-04", "2026-03-09"],"amount": ["1,200", "350", "n/a"],"qty": ["3", "1", "2"],})print(orders.dtypes)orders["order_date"] = pd.to_datetime(orders["order_date"])orders["amount"] = pd.to_numeric(orders["amount"].str.replace(",", ""), errors="coerce")orders["qty"] = orders["qty"].astype(int)print(orders.dtypes)print(orders["order_date"].dt.day_name().tolist())print(orders["amount"].sum())
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
order_date object
amount object
qty object
dtype: object
order_date datetime64[ns]
amount float64
qty int64
dtype: object
['Sunday', 'Wednesday', 'Monday']
1550.0 ๐ฏ Convert "price" to numbers (bad values become NaN) and "sold_on" to dates. Then set total to the sum of price.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
items["price"] = pd.to_numeric(items["price"], errors="coerce"); items["sold_on"] = pd.to_datetime(items["sold_on"]); total = items["price"].sum()
- 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. - The Python idea
pd.to_numeric(df["col"], errors="coerce")A column often loads as text (object) even when it holds numbers or dates. - In real lifeAn e-commerce team converts order timestamps with
to_datetimeand then groups bydt.hourto 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 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.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Finding and removing duplicates โ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"withto_numericandto_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
- pandas.to_datetime (docs.python.org)
- pandas.to_numeric (docs.python.org)