Sub topic 1
Checking what dtypes you actually have
Prerequisites
This chapter assumes you can do the following:
- Write basic Python, including functions and list comprehensions.
- Create a pandas DataFrame and Series and select columns from them.
- Read a CSV file with
pd.read_csv.
You don't need to know how to convert types yet. Later chapters cover that. This chapter is about looking first, so you know which columns need work and why.
Why look before you convert
A dtype (data type) is the type pandas assigns to every value in a column. It decides which operations work, how much memory the column uses, and how missing values are stored. If a numeric column has the wrong dtype, sum() can concatenate strings instead of adding numbers, sorting can put "10" before "9", and date arithmetic fails.
Wrong dtypes rarely raise errors on their own. The code runs and the results are quietly wrong. So the first step in any cleaning job is an audit of what you actually have, not what the column names suggest.
Reading `df.dtypes`
DataFrame.dtypes returns a Series. Its index holds the column names and its values hold the dtypes. Here is a small frame that looks like messy CSV data:
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)price object
qty object
date object
dtype: objectEvery column is object, even though qty holds digits and date holds dates. pandas never guesses that text is a number or a date when you build a frame from strings. The next chapter explains how columns end up this way.
In pandas 3 and later, text columns default to a dedicated string dtype that prints as str. In pandas 2.x they print as object. The advice here is the same in both cases: a text-like dtype on a column that should be numeric or a date is a sign something needs converting.
Common dtypes you will see:
| dtype | Holds | Notes |
|---|---|---|
| `int64` | Whole numbers | Cannot hold missing values |
| `float64` | Decimal numbers | Also what integers with gaps become |
| `bool` | True/False | Cannot hold missing values |
| `object` | Anything | Usually Python strings, but can mix types |
| `datetime64[ns]` | Timestamps | Missing values are `NaT` |
| `category` | Repeated labels | Stores integer codes plus a list of labels |
| `Int64`, `boolean`, `string` | Nullable versions | Capitalized names, support `pd.NA` |
Capitalization matters. int64 is the NumPy-backed type. Int64 is the pandas nullable type. They behave differently with missing data, and a later chapter covers this.
Reading `df.info()`
df.info() prints a summary to the screen. It gives you the dtype and the count of non-null values for each column, along with the index type and the memory estimate.
df.info()<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 price 3 non-null object
1 qty 3 non-null object
2 date 3 non-null object
dtypes: object(3)
memory usage: ... bytesThe two tools answer different questions:
df.dtypesreturns a Series you can filter, compare, or loop over in code.df.info()prints text for reading. It returnsNone, so you can't store its result.
The Non-Null Count column is useful. If a column has fewer non-null values than there are rows, you have missing data. Notice that price shows 3 non-null even though it contains "n/a". That value is just a string to pandas, so it isn't counted as missing. Strings like "n/a", "-", or "unknown" are a common source of hidden missing data.
On wide frames, info() may abbreviate its output. Pass verbose=True to list every column.
Spotting a wrong dtype
Compare each column's dtype with what its values mean. These patterns show up often:
- A numeric column is
object. At least one value is text, such as a currency symbol, a thousands separator, or a placeholder like"n/a". Loading from CSV turns the whole column into text if even one cell can't be parsed as a number. - A date column is
object. pandas does not parse dates unless you ask it to. - An integer column is
float64. A missing value is present. Plainint64has no way to store a gap, so pandas upcasts to float and storesNaN. - An ID or code column is numeric. Zip codes like
02134lose their leading zero when read as integers. These columns should be text. - A flag column is
object. Values such as"yes"and"no"are strings, not booleans.
The float case is easy to miss. You can see it directly:
print(pd.Series([1, 2, 3]).dtype)
print(pd.Series([1, 2, None]).dtype)int64
float64An unexpected float64 on a column of counts is a clue to look for missing values.
Looking inside an object column
The dtype object only tells you pandas stores Python objects. It doesn't say which objects. A column can hold strings, numbers, None, or a mix, and dtypes shows object for all of them. To see the real contents, count the Python type of each value:
mixed = pd.Series([1, "2", 3.5, None, "x"])
print(mixed.dtype)
print(mixed.map(type).value_counts())The dtype is object. The counts show two str values, one int, one float, and one NoneType. A column like this needs cleaning before conversion, and the type counts tell you which kinds of values to handle.
You can also test whether every string in a column looks like a number, without converting anything:
print(df["qty"].str.fullmatch(r"\d+").all())This prints True because every value in qty is made only of digits. The same check on price would return False, which tells you cleaning is needed first.
Selecting columns by dtype
select_dtypes returns a new frame with only the columns of the dtypes you name. It is a quick way to split a wide frame into groups:
numeric_cols = df.select_dtypes(include="number").columns
print(list(numeric_cols))For the frame above this prints []. Seeing an empty list when you expect numeric columns is itself a finding. You can also exclude types with exclude=, and you can pass a list such as include=["number", "datetime"].
To count how many columns have each dtype, use value_counts on the dtypes Series:
print(df.dtypes.value_counts())A reusable audit function
When you receive a new dataset, the same questions come up each time: what dtype is each column, how many values are present, how many distinct values are there, and what does a typical value look like? This function answers all four in one table:
def dtype_report(frame):
return pd.DataFrame({
"dtype": frame.dtypes.astype(str),
"non_null": frame.notna().sum(),
"unique": frame.nunique(),
"sample": frame.apply(
lambda col: col.dropna().iloc[0] if col.notna().any() else None
),
})
print(dtype_report(df))The sample column shows the first present value in each column. A numeric-looking dtype with a sample like $1,200 points straight at the problem. A very low unique count on a text column suggests it may suit the category dtype, which a later chapter covers.
Checking memory
df.info() reports memory by default as an estimate. For object columns the estimate counts only the pointers, 8 bytes per value on a 64-bit build, and not the strings they point to. To measure the real size, ask for a deep count:
s = pd.Series(["alpha", "beta", "gamma"] * 1000)
print(s.memory_usage())
print(s.memory_usage(deep=True))For object data, the second number is much larger than the first, because it includes the size of each Python string. Use df.memory_usage(deep=True) for per-column figures, or df.info(memory_usage="deep") for the summary. This matters later, when you compare the cost of text columns against categories and downcast numbers.
A checking workflow
The diagram shows the order of checks to run on each new dataset.
The arrow from the last step back to df.info is deliberate. After every conversion, check the dtypes again. A conversion that silently did nothing, or turned everything into missing values, is easy to catch if you look right after.
Common mistakes
- Trusting the column name. A column named
pricecan be text. Always check the dtype. - Reading
objectas "string". It can mean mixed types. Count them withmap(type). - Missing the hidden missing values.
"n/a", empty strings, and"-"are not counted as null byinfo(). - Using the default memory estimate for object columns. It undercounts. Use
deep=True. - Skipping the recheck. Run
dtypesagain after each change.
Exercise
A column called age shows dtype float64, and you expected whole numbers. What is the most likely cause, and how would you confirm it?
Show answer
The column most likely contains missing values. Plain int64 can't store them, so pandas stores the column as float64 with NaN. Confirm it with df["age"].isna().sum(), or by checking that the Non-Null Count in df.info() is lower than the number of rows.
Exercise
A column code has dtype object. How do you find out whether it holds only strings or a mix of Python types? Write the line of code.
Show answer
df["code"].map(type).value_counts(). This counts the Python type of each value, so a mix of str, int, float, and NoneType shows up as separate rows.