Sub topic 4
dtypes and converting types
This chapter assumes you can build a Series and a DataFrame, and that you know a column is a Series with an Index. You should also be comfortable reading short Python snippets. No NumPy knowledge is needed.
What a dtype is
A dtype (data type) describes what kind of values a Series holds and how pandas stores them. Every Series has exactly one dtype. A DataFrame has one dtype per column, so a single table can mix integers, text, and dates.
The dtype decides which operations work and how fast they run. It also decides how missing values are represented. Many pandas surprises come from a column having a different dtype than you expected.
import pandas as pd
df = pd.DataFrame({
"id": [1, 2, 3],
"price": [9.5, 12.0, 7.25],
"name": ["pen", "book", "cup"],
"in_stock": [True, False, True],
})
print(df.dtypes)
df.info()df.dtypes returns a Series whose index is the column names and whose values are dtypes. df.info() adds non-null counts and memory use. Run one of them right after loading any data.
Common dtypes
| dtype | Holds | Missing value |
|---|---|---|
| `int64` | whole numbers | not supported, so a missing value forces `float64` |
| `float64` | decimal numbers | `NaN` |
| `bool` | `True` and `False` | not supported, so a missing value forces `object` |
| `object` | any Python objects, usually strings | `None` or `NaN` |
| `datetime64[ns]` | timestamps | `NaT` |
| `category` | a fixed set of labels | `NaN` |
| `Int64`, `boolean`, `string` | nullable versions | `<NA>` |
The object dtype is the fallback. A column of strings is usually object, and so is a column that mixes numbers and text. Operations on object columns run as Python loops, so they are slower, and they can hide mistakes.
How pandas infers dtypes
When you build a Series, pandas picks the narrowest dtype that fits all the values.
import pandas as pd
print(pd.Series([1, 2, 3]).dtype) # int64
print(pd.Series([1, 2, None]).dtype) # float64
print(pd.Series([1, "a", 3]).dtype) # object
print(pd.Series([True, False]).dtype) # bool
print(pd.Series([True, None]).dtype) # objectThe second line shows the most common surprise. One missing value turns integers into floats, because int64 has no way to store a missing entry. The float column holds NaN instead, and your ids become 1.0, 2.0.
The same inference happens in read_csv. If one cell in a numeric column contains text such as "N/A" or "-", the entire column becomes object. When arithmetic fails on a column that looks numeric, check its dtype first.
Converting with astype
astype returns a new Series or DataFrame with the requested dtype. It does not change the original.
import pandas as pd
s = pd.Series(["1", "2", "3"])
print(s.dtype) # object
n = s.astype("int64")
print(n.dtype) # int64
print((n + 1).tolist()) # [2, 3, 4]
f = pd.Series([1.9, 2.1, -0.5]).astype("int64")
print(f.tolist()) # [1, 2, 0]Converting floats to integers truncates toward zero. It does not round, so 1.9 becomes 1. Call .round() first if you want rounding.
astype is strict. It raises an error if any value cannot be converted:
import pandas as pd
raw = pd.Series(["10", "20", "abc"])
try:
raw.astype("int64")
except ValueError as err:
print("failed:", err)You can also convert several columns at once by passing a dictionary, as in df.astype({"id": "int32", "price": "float32"}). Columns not named in the dictionary are left alone.
Converting messy data with to_numeric and to_datetime
For data from files or users, use the dedicated converters. They give you control over bad values through the errors argument.
import pandas as pd
raw = pd.Series(["10", "20", "abc", None])
print(pd.to_numeric(raw, errors="coerce").tolist())
# [10.0, 20.0, nan, nan]
dates = pd.to_datetime(pd.Series(["2024-01-05", "2024-02-10", "not a date"]),
errors="coerce")
print(dates)
print(dates.dtype) # datetime64[ns] in pandas 2.xWith errors="coerce", anything that cannot be parsed becomes NaN (or NaT for dates). With the default errors="raise", the first bad value stops the conversion.
Coercion hides data problems unless you check for them. A common pattern is to compare missing counts before and after:
import pandas as pd
raw = pd.Series(["10", "20", "abc", None])
clean = pd.to_numeric(raw, errors="coerce")
newly_missing = clean.isna() & raw.notna()
print(raw[newly_missing].tolist()) # ['abc']This lists the values that were present but failed to parse. You can then decide whether to fix them or drop them.
Nullable dtypes
The nullable dtypes Int64, Float64, boolean, and string can hold a missing value without changing the type. The capital letter in Int64 distinguishes it from NumPy's int64.
import pandas as pd
s = pd.Series([1, 2, None], dtype="Int64")
print(s)
print(s.dtype) # Int64
ids = pd.Series([1.0, 2.0, None]).astype("Int64")
print(ids.tolist()) # [1, 2, <NA>]Missing entries show as <NA> rather than NaN. Use these dtypes when a column must stay integer or boolean even though it has gaps, such as an optional id.
df.convert_dtypes() converts every column to the best nullable dtype it can find. It is a quick way to clean up a freshly loaded table, but check the result, because it may change columns you wanted to keep as they were.
Gotchas
Converting to bool
astype(bool) follows Python truthiness. Every non-empty string is True, including "False".
import pandas as pd
flags = pd.Series(["True", "False", "False"])
print(flags.astype(bool).tolist()) # [True, True, True]
mapped = flags.map({"True": True, "False": False})
print(mapped.tolist()) # [True, False, False]Use map with an explicit dictionary when you convert text to booleans. Values missing from the dictionary become NaN, which also makes bad input visible.
Integers with missing values
Calling astype("int64") on a column that contains NaN raises an error. Fill or drop the missing values first, or convert to Int64.
Silent downcasting
Converting to a smaller type such as int8 can overflow. pd.Series([200]).astype("int8") does not give you 200. The result depends on the pandas and NumPy versions, and some versions raise an error. Check the value range before you shrink a type.
Converting does not fix the source
astype returns a new object. Write df["id"] = df["id"].astype("int64") or the column stays unchanged. Assigning back is the usual way to keep a conversion.
Category dtype
A category column stores each distinct label once and keeps a small integer code per row. It suits columns with few distinct values repeated many times, such as region or status.
import pandas as pd
s = pd.Series(["EU", "SA", "AS", "EU"] * 1000)
c = s.astype("category")
print(c.dtype) # category
print(c.cat.categories.tolist()) # ['AS', 'EU', 'SA']
print(s.memory_usage(deep=True) > c.memory_usage(deep=True)) # TrueMemory use is covered in detail in a later chapter. For now, treat category as a way to say that a column holds labels from a fixed set.
Exercise
A column qty is read from a CSV as object because it contains the values "4", "7", "n/a", and "12". You need an integer column that keeps the missing entry as missing. Write the two steps that produce it, and say why astype("int64") cannot be used directly.
Show answer
Use pd.to_numeric(df["qty"], errors="coerce") to turn "n/a" into NaN, which gives float64. Then call .astype("Int64") on the result to get a nullable integer column with <NA> for the bad entry. Calling astype("int64") directly fails because "n/a" cannot be parsed as an integer, and even after parsing, plain int64 cannot store a missing value.