Sub topic 1
Checking what dtypes you actually have
Prerequisites
This chapter assumes basic Python, creating and indexing pandas DataFrame and Series objects, and reading CSV files with pandas.
A pandas dtype is the kind of value stored in a column. For example, int64 stores integers, float64 stores decimal numbers, and datetime64[ns] stores dates and times. Check dtypes before calculating, sorting, or filtering:
import pandas as pd
df = pd.DataFrame({
"price": ["$1,200", "$85", "n/a"],
"qty": ["3", "5", "7"],
"date": ["2024-01-05", "2024-02-10", "bad"],
})
print(df.dtypes)
df.info()df.dtypes gives one dtype per column. df.info() also shows non-missing counts and memory use. A column that looks numeric but has dtype object needs investigation.
Why numbers and dates end up as `object`
object is pandas’ general-purpose dtype. It often appears when a column contains strings, or when pandas cannot represent every value with one specialized dtype. A currency symbol, a spelling error, or mixed values can force the whole column to remain object:
print(df["price"].dtype) # objectThe values may look like numbers to you, but pandas sees text such as "$1,200". Arithmetic on that text will not behave like numeric arithmetic. The same issue affects dates: "2024-01-05" is text until pandas parses it as a date.
flowchart TD
A[Inspect df.dtypes] --> B{Correct dtype?}
B -->|Yes| C[Use the column]
B -->|No| D[Clean text]
D --> E[Convert safely]Converting a column with `astype`
Use astype when the values already have a compatible, predictable form. For example, strings containing only whole numbers can become integers:
df["qty"] = df["qty"].astype("int64")
print(df["qty"].dtype)astype raises an error when a value cannot be converted. That default is useful because it prevents bad data from disappearing unnoticed. It is less suitable for messy input where you need to inspect invalid values individually.
Cleaning strings before you convert
Remove formatting that belongs to presentation, not to the value. For currency, remove the dollar sign and comma first:
df["price"] = df["price"].str.replace(r"[$,]", "", regex=True)
print(df["price"])The column is still text after this step. A later conversion with pd.to_numeric(..., errors="coerce") can turn valid text into numbers and represent invalid text as missing. Always inspect which values became missing before accepting the result.
Exercise
Why can a column containing "3", "5", and "bad" have dtype object?
Show answer
The values are strings, and the invalid or mixed content prevents pandas from treating the whole column as a numeric type.