Sub topic 2
Why Numbers and Dates End Up as object
This chapter assumes you can build a DataFrame, select columns, and load a CSV with pd.read_csv. It explains why pandas leaves some columns as object when you expected numbers or dates. The next chapters cover the fixes. Here the goal is to diagnose the cause.
What object means
pandas stores most columns in a NumPy array with a fixed-width type such as int64, float64 or datetime64[ns]. Every cell in such an array takes the same number of bytes, so pandas can add, compare and sort values quickly.
The object dtype is the fallback. The array holds references to arbitrary Python objects, and each cell can be a different type. pandas cannot assume anything about the values, so it treats them as generic Python objects.
In recent pandas versions, a text column may show as string or str instead of object. Which one you see depends on the version and settings. The diagnosis in this chapter is the same either way: the column holds text, not numbers or timestamps.
How a numeric column falls back to object
When read_csv reads a column, it tries to parse the whole column as one type. It tries integers, then floats, then booleans. If any value fails, the parser does not keep the good values and flag the bad ones. The entire column stays as text.
import io
import pandas as pd
csv = (
"id,amount,when\n"
"1,10,2024-01-05\n"
"2,20,2024-01-06\n"
"3,unknown,2024-01-07\n"
)
df = pd.read_csv(io.StringIO(csv))
print(df.dtypes)id is int64. amount is object (or str) because of one entry, unknown. Rows 1 and 2 contain perfectly good numbers, but they are stored as the text "10" and "20".
One bad cell can change the dtype of a column with a million rows.
flowchart TDThe diagram below shows the decision the parser makes for each column.
The usual causes for numbers
Most numeric columns that load as object have one of these problems.
| Cause | Example values | Why parsing fails |
|---|---|---|
| Currency symbols | `$1,200` | `$` is not part of a number |
| Thousands separators | `1,200` | The comma is not parsed by default |
| Units or suffixes | `12kg`, `45%` | Letters and `%` are not numeric |
| Placeholder text | `unknown`, `-`, `?` | Not in the default missing-value list |
| Stray whitespace | `" 42"`, `"42 "` | Usually tolerated, but non-breaking spaces are not |
| Mixed formats | `1.5` and `1,5` | Decimal comma versus decimal point |
Some placeholders are handled for you. read_csv treats NA, n/a, NaN, null and the empty string as missing by default, so a column that only contains those alongside numbers loads as float64. A placeholder that is not on that list, like unknown, forces the whole column to text. The na_values argument of read_csv lets you add your own.
Inspecting what is really in the column
The dtype tells you the column is text. It does not tell you which cells caused it. The map(type) trick shows the Python type of each cell.
mixed = pd.Series([1, "2", 3.5, None, "four"])
print(mixed.dtype)
print(mixed.map(type).value_counts())This series has object dtype and contains an int, two str values, a float and a NoneType. A column that came out of read_csv is usually all str plus NaN. A column built from Python lists, JSON or Excel can hold several types at once.
To look at the suspicious cells directly, check which ones fail a numeric parse.
amount = df["amount"]
parsed = pd.to_numeric(amount, errors="coerce")
print(amount[parsed.isna() & amount.notna()])errors="coerce" turns unparseable values into NaN. Comparing the result with the original shows which non-missing values were lost. Later chapters build on this pattern.
Why dates end up as object
Dates behave differently from numbers. read_csv does not try to detect dates unless you ask. A column like 2024-01-05 is just text to the parser, so it loads as object even when every value is a valid date.
print(df["when"].dtype)
print(df["when"].iloc[0], type(df["when"].iloc[0]))The values are strings like '2024-01-05'. You can still sort them and they happen to sort correctly, because ISO format (YYYY-MM-DD) is ordered alphabetically. That hides the problem. You cannot subtract two of them, extract the month with .dt.month, or resample by week.
Other reasons a date column stays as object:
- You passed
parse_dates, but one value is not a date (bad,TBD). The column falls back to text. - The column mixes formats, such as
2024-01-05and05/01/2024. A single format string will not parse both. - The values are Python
datetime.dateobjects, notdatetime.datetime. pandas keepsdateobjects asobject. - Time zone offsets differ between rows, for example
+01:00and+02:00. Mixed offsets cannot fit in onedatetime64column, so pandas keeps them asobjector raises an error, depending on the version.
The datetime.date case surprises many people.
import datetime
d = pd.Series([datetime.date(2024, 1, 5), datetime.date(2024, 1, 6)])
print(d.dtype)
print(pd.to_datetime(d).dtype)The first print shows object. After pd.to_datetime, the dtype is datetime64[ns] (or another unit in newer versions).
Why it matters
Text that looks like numbers behaves like text. Operations still run, but the results are wrong, and pandas often gives no warning.
s = pd.Series(["10", "9", "100"])
print(s.sort_values().tolist())
print((s == 10).tolist())The sort gives ['10', '100', '9'], which is alphabetical order, not numeric order. The comparison s == 10 is False for every row because the text "10" is not equal to the integer 10.
Other consequences:
- Aggregations like
mean()fail with aTypeError, or on some pandas versions give odd results. - Memory use is much higher, because each cell is a separate Python object.
- Operations are slower, because pandas loops over Python objects instead of using vectorized arrays.
- Merges between a text key and a numeric key silently match nothing, or raise an error.
Intentional object columns
Not every object column is a mistake. Some identifiers should stay as text:
- Zip codes with leading zeros (
02134) - Phone numbers
- Product codes such as
00042 - Account numbers too long for
int64
You do not do arithmetic on these, and converting them to integers would drop the leading zeros. Decide per column. Convert quantities and measurements. Keep identifiers as text, and use the string dtype to make that choice explicit.
A diagnostic routine
When a column has the wrong dtype, work through these steps in order:
- Run
df.dtypesordf.info()to find the suspect columns. - Check
df[col].map(type).value_counts()to see whether the cells are all text or a mix of types. - Look at
df[col].unique()ordf[col].sample(10)for symbols, units or placeholders. - Use
pd.to_numeric(..., errors="coerce")orpd.to_datetime(..., errors="coerce")and list the rows that become missing. - Decide whether to clean the text, add values to
na_values, or leave the column as text.
This keeps you from converting blindly and discarding data you needed.
Exercise
A CSV column weight contains the values 5, 7, 12, unknown. After pd.read_csv, the dtype is object. Why are 5, 7 and 12 also stored as text, and which read_csv argument could let the column load as numbers?
Show answer
The parser converts a whole column or none of it. The single value unknown is not in the default missing-value list, so parsing as a number fails and every value stays text. Passing na_values=["unknown"] makes read_csv treat that entry as missing, and the column then loads as float64.
Exercise
A Series holds datetime.date(2024, 1, 5) objects and has dtype object. Which call gives it a datetime dtype, and why does it not happen automatically?
Show answer
pd.to_datetime(series) converts it to datetime64. pandas keeps datetime.date objects as object because they are arbitrary Python objects, and it only changes the dtype when you request a conversion.