Sub topic 12
Letting pandas pick better dtypes with convert_dtypes
This chapter assumes you can build a DataFrame, read a CSV with pd.read_csv, and use df.dtypes. It also assumes you know the earlier chapters' tools: astype, pd.to_numeric, and the idea of nullable dtypes such as Int64. Here you will learn what convert_dtypes does, what it leaves alone, and when to prefer it over converting columns one at a time.
What convert_dtypes does
DataFrame.convert_dtypes() and Series.convert_dtypes() look at the values already in each column and move the column to the best matching nullable dtype. It never parses text. It only re-labels data that is already numeric, boolean or string-like.
The default mapping is:
| Starting dtype or content | Result |
|---|---|
| `object` holding only strings (and missing values) | `string` |
| `int64` | `Int64` |
| `float64` where every non-missing value is a whole number | `Int64` |
| `float64` with fractional values | `Float64` |
| `bool`, or `object` holding only True, False and missing values | `boolean` |
| `datetime64`, `category`, `timedelta64` | unchanged |
| `object` with mixed Python types | unchanged (`object`) |
The method returns a new object. It does not modify the original.
A first example
The frame below mixes the kinds of columns that commonly appear after loading data with missing values.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", None],
"age": [25.0, 30.0, np.nan],
"score": [1.5, 2.5, np.nan],
"active": [True, False, None],
"count": [1, 2, 3],
})
print(df.dtypes)
print()
better = df.convert_dtypes()
print(better.dtypes)
print()
print(better)Before the call, name and active are object, age and score are float64, and count is int64. After the call, the dtypes are:
name:stringage:Int64score:Float64active:booleancount:Int64
Notice age. It was float64 only because NumPy integers cannot hold NaN, so pandas stored whole numbers as floats. convert_dtypes notices that every non-missing value is a whole number and restores an integer type. The missing entry is now <NA> rather than NaN.
What it does not do
The most common mistake is expecting convert_dtypes to repair text that looks like numbers or dates. It does not.
raw = pd.DataFrame({
"qty": ["3", "5", "7"],
"price": ["$1,200", "$85", "n/a"],
"date": ["2024-01-05", "2024-02-10", "2024-03-01"],
})
print(raw.convert_dtypes().dtypes)All three columns come back as string. The values "3", "5" and "7" are still text. convert_dtypes only decides which text dtype to use.
To get real numbers or dates, parse first and then call convert_dtypes. Parsing decides what the values mean. convert_dtypes then picks the storage type.
raw = pd.DataFrame({
"qty": ["3", "5", None],
"price": ["$1,200", "$85", "n/a"],
"date": ["2024-01-05", "2024-02-10", "bad"],
})
clean = raw.assign(
qty=pd.to_numeric(raw["qty"]),
price=pd.to_numeric(
raw["price"].str.replace(r"[$,]", "", regex=True),
errors="coerce",
),
date=pd.to_datetime(raw["date"], format="%Y-%m-%d", errors="coerce"),
).convert_dtypes()
print(clean.dtypes)
print(clean)pd.to_numeric turns qty into float64 because of the missing value. convert_dtypes then turns it into Int64. This is a convenient way to avoid choosing between int and float yourself. The price column has no missing text after cleaning except the coerced NaN, so it becomes Int64 as well, because 1200.0 and 85.0 are whole numbers. The date column stays datetime64[ns], and the bad value is NaT.
Controlling what gets converted
Each type of conversion has a switch. All default to True.
| Argument | Effect when set to `False` |
|---|---|
| `infer_objects` | Do not try to infer a better type for `object` columns first |
| `convert_string` | Leave text columns as `object` |
| `convert_integer` | Keep whole-number floats as `Float64` instead of `Int64` |
| `convert_boolean` | Leave boolean-like columns as they are |
| `convert_floating` | Leave float columns as they are |
The convert_integer switch matters most in practice. Consider a column of measurements that happen to be whole numbers:
temps = pd.Series([20.0, 21.0, 19.0, np.nan], name="temp_c")
print(temps.convert_dtypes().dtype)
print(temps.convert_dtypes(convert_integer=False).dtype)The first call gives Int64. The second gives Float64. If later values might be 20.5, keeping a float type is safer, because the integer type would reject a fractional assignment. Use convert_integer=False whenever a column is conceptually continuous.
You can also convert only some columns. convert_dtypes applies to the whole frame, so select a subset and assign it back:
cols = ["age", "count"]
df[cols] = df[cols].convert_dtypes()
print(df.dtypes)Choosing a backend
By default, the result uses pandas' own nullable extension types (Int64, Float64, boolean, string). In pandas 2.0 and later you can ask for Arrow-backed types instead:
arrow = df.convert_dtypes(dtype_backend="pyarrow")
print(arrow.dtypes)This requires the pyarrow package. The dtypes print as names such as int64[pyarrow] and string[pyarrow]. Arrow-backed columns can use less memory for text and interoperate with other Arrow-based tools. The default "numpy_nullable" backend is the more conservative choice, and its types are better supported by older libraries. pd.read_csv accepts the same dtype_backend argument, so you can get nullable types at load time without a second pass.
Behavior to watch for
Some effects of convert_dtypes catch people off guard.
- Whole-number floats become integers. A float column like
[1.0, 2.0, 3.0]becomesInt64even when you meant it as floats. Useconvert_integer=Falsefor those columns. - Missing values change representation.
NaNbecomes<NA>. Code that testsx != xor relies onnp.nanwill not behave the same way. pd.NAhas three-valued logic. In abooleancolumn,pd.NA & FalseisFalse, butbool(pd.NA)raises aTypeError. Anifstatement that tests a single value from the column can fail where it used to pass.- Mixed
objectcolumns are untouched. A column holding both numbers and strings staysobject. That is usually a sign of a parsing problem to fix first. - Version differences. In recent pandas versions, text columns may already load with a string dtype by default.
convert_dtypesis still useful for the numeric and boolean columns, but checkdf.dtypesbefore and after rather than assuming what changed. - Downstream libraries. Some plotting and machine learning libraries expect NumPy dtypes. If a call fails on a nullable column, convert that column back with
astype("float64")after filling or dropping missing values.
When to use it
convert_dtypes suits exploratory work, quick scripts, and inspection of data you did not produce. It saves you from writing a conversion for each column.
For pipelines that run repeatedly, explicit dtypes are better. Passing dtype and parse_dates to read_csv, or calling astype with a schema dictionary, gives the same result every run. convert_dtypes infers from the values it sees, so a column that is whole-number today may contain a fraction in tomorrow's file and quietly come out as Float64. A pipeline that depends on Int64 would then break on a different line far from the cause.
A practical compromise is to use convert_dtypes once on a sample, read the dtypes it chose, and write them down as an explicit mapping:
schema = better.dtypes.astype(str).to_dict()
print(schema)You can then pass those names to astype or read_csv in your production code.
Exercises
Exercise
A DataFrame has a column id that holds the strings "101", "102", "103". After calling df.convert_dtypes(), what is the dtype of id, and what should you do to get an integer column?
Show answer
The dtype is string, because convert_dtypes does not parse text. Convert it with pd.to_numeric(df["id"]) (or astype("Int64") for clean whole-number text), then call convert_dtypes if you want pandas to choose the nullable type.
Exercise
The series s = pd.Series([4.0, 8.0, np.nan]) stores average ratings that may later become fractional. Write the call that converts it to a nullable type while keeping it a float type, and state the resulting dtype.
Show answer
s.convert_dtypes(convert_integer=False) gives Float64. Without convert_integer=False, the whole-number values would produce Int64.
Exercise
Why is convert_dtypes risky as the only dtype step in a nightly pipeline that loads a new CSV each day?
Show answer
It infers dtypes from the values present in that file. A column of whole numbers can become Int64 one day and Float64 the next if a fractional value appears, and text that failed to parse stays string. Explicit dtype and parse_dates arguments give the same schema every run.