Sub topic 6
Converting Column Types
This chapter assumes you can build a DataFrame, select a column by name, and know that a column is a Series with a single dtype. Wrong dtypes are a common cause of silent bugs. Text numbers sort alphabetically, dates can't be subtracted, and arithmetic raises errors. Converting a column produces a new Series, so you assign the result back.
Check dtypes first
Use df.dtypes to see what pandas inferred. A column of strings has dtype object (or string in newer setups). Numbers read from messy files often arrive as object because one bad cell makes the whole column text.
import pandas as pd
df = pd.DataFrame({
"id": ["1", "2", "3"],
"price": ["1.5", "12.0", "x"],
"when": ["2026-01-15", "2026-02-03", "2026-03-09"],
})
print(df.dtypes)Three tools, three jobs
| Tool | Use it for | On bad values |
|---|---|---|
| `astype` | Clean data and a known target type | Raises an error |
| `pd.to_numeric` | Text that should be numbers | `errors="coerce"` gives NaN |
| `pd.to_datetime` | Text that should be dates | `errors="coerce"` gives NaT |
astype
astype converts the whole column to one type. It is strict, so it fails if any value can't convert.
df["id"] = df["id"].astype(int)Running df["price"].astype(float) on the data above raises a ValueError because of "x". That failure is useful when bad data should stop your pipeline.
to_numeric
When some bad values are expected, use to_numeric with errors="coerce". Unparseable entries become NaN (missing), and the column becomes float64.
df["price"] = pd.to_numeric(df["price"], errors="coerce")
print(df["price"])to_datetime
to_datetime parses strings into datetime64 values. After this, the .dt accessor (covered in a later chapter) and date arithmetic work.
df["when"] = pd.to_datetime(df["when"])
print(df["when"].max() - df["when"].min())If your dates use a fixed layout, pass format="%Y-%m-%d". This is faster and avoids misreading day-first and month-first dates.
raw = pd.Series(["15/01/2026", "03/02/2026"])
dates = pd.to_datetime(raw, format="%d/%m/%Y")
print(dates)Common errors
- Integers with missing values.
astype(int)fails if the column containsNaN, because the defaultint64can't hold missing values. Use the nullable type"Int64"(capital I), which stores missing values as<NA>. - Forgetting to assign back.
df["price"].astype(float)returns a new Series and leavesdfunchanged. - Silent coercion.
errors="coerce"hides bad data. Count the new missing values withdf["price"].isna().sum()to see how many cells failed. - Thousands separators. Strings like
"1,200"fail to parse. Remove the commas with.str.replace(",", "")first.
ids = pd.Series(["1", "2", None])
print(pd.to_numeric(ids).astype("Int64"))The category dtype is also worth knowing. It stores repeated labels compactly: df["tier"].astype("category").
Exercise
A column qty holds the strings "4", "7", "n/a". Write one line that converts it to numbers and leaves the bad entry as NaN. Why does astype(int) fail here?
Show answer
df["qty"] = pd.to_numeric(df["qty"], errors="coerce"). astype(int) is strict and raises a ValueError on "n/a". Also, even after coercion the column holds NaN, so it is float64 rather than int64. Use .astype("Int64") if you need integers with missing values.
Exercise
You parse the dates "04/05/2026" with pd.to_datetime and no format. Why is this risky, and how do you fix it?
Show answer
The string can mean 4 May or April 5, so pandas may guess wrong. Pass an explicit format, such as format="%d/%m/%Y", to remove the ambiguity.