Sub topic 1
Checking what dtypes you actually have
Prerequisites
This chapter assumes you can write basic Python and create a pandas DataFrame or Series. You should also have read a CSV file with pd.read_csv. Later chapters in this tutorial fix the problems you find here. This one only teaches you to see them.
Why check first
A dtype is the data type pandas uses to store a column, such as int64, float64, datetime64[ns] or object. The dtype decides which operations work. You can add numbers, but you can't sort dates stored as text in calendar order. Wrong dtypes often cause no error, so you only notice them when a total or a sort looks wrong. Inspect dtypes before you clean anything.
A frame with the wrong types
The frame below looks like data loaded from a messy CSV. Every value is a string.
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()All three columns are text. Depending on your pandas version, the dtype prints as object or str. Older versions use object. Newer versions may use a dedicated string dtype. This tutorial treats both as "text".
Reading df.dtypes
df.dtypes returns a Series with one dtype per column. It is the quickest check. You can also read the dtype of one column with df["qty"].dtype.
Reading df.info()
df.info() prints more. It shows the row count, each column's name, its non-null count and its dtype. It also shows total memory use. The non-null count is useful because it exposes missing values. A column with fewer non-null values than rows has gaps.
Note that info() prints directly and returns None. Don't wrap it in print().
placeholderRemove that thought: the table below compares the two tools instead.
| Tool | Returns | Shows non-null counts | Shows memory |
|---|---|---|---|
| `df.dtypes` | A `Series` of dtypes | No | No |
| `df.info()` | Prints a summary, returns `None` | Yes | Yes |
Spotting a column with the wrong type
Compare each dtype with what the column should hold. These are the usual mismatches:
priceorqtyis text when it should be numeric.dateis text when it should bedatetime64.- An ID such as a zip code is numeric when it should be text, so a leading zero is lost.
- A column of repeated labels such as
statusis text when it could becategory.
In this frame, price should be float64, qty an integer and date a datetime. Nothing in the output warns you. pandas reports what it has, not what you meant.
Looking inside an object column
The object dtype can hold anything. A column of numbers mixed with strings is also object. To see what is really inside, count the Python type of each value:
s = pd.Series([1, "2", 3.0, None])
print(s.dtype)
print(s.map(type).value_counts())The dtype is object, and the counts show an int, a str, a float and a NoneType. A mix like this explains why later conversions fail on some rows only.
Checking many columns at once
On wide frames, summarize instead of reading every line:
print(df.dtypes.value_counts())
text_cols = df.select_dtypes(include="object").columns
print(list(text_cols))value_counts() tells you how many columns have each dtype. select_dtypes lists the columns of a given dtype. If your pandas version shows str instead of object, use include=["object", "str"].
Next steps
You now have a routine: run df.info(), compare each dtype with the intended one, and look inside object columns with map(type). The next chapters explain why columns become object and how to convert them.
Exercise
You load a CSV and df.info() shows order_id as int64, but some IDs such as 00457 have lost their leading zeros. What does this tell you about the dtype, and what should the dtype be?
Show answer
The column was parsed as numbers, which drops leading zeros. IDs are labels, not quantities, so the dtype should be text (string or object). Fixing it at load time with the dtype argument of read_csv avoids the loss.
Exercise
A column shows dtype object. Which expression reveals whether it holds a mix of Python types?
Show answer
df["col"].map(type).value_counts(). It counts how many values are str, int, float and so on.