Sub topic 12
Letting pandas pick better dtypes with convert_dtypes
This chapter assumes you can inspect dtypes with df.dtypes, convert with astype and pd.to_numeric, and know what Int64 and boolean are. DataFrame.convert_dtypes() is a shortcut that moves columns to the nullable dtypes you saw earlier in one call.
What convert_dtypes does
convert_dtypes() looks at the values in each column and returns a new DataFrame whose columns use the best-fitting nullable dtype. It applies these rules:
| Current dtype or content | Result |
|---|---|
| `object` column of strings | `string` |
| `int64` | `Int64` |
| `float64` with only whole numbers (and NaN) | `Int64` |
| `float64` with fractions | `Float64` |
| `bool`, or `object` holding True, False and None | `boolean` |
A worked example
import pandas as pd
df = pd.DataFrame({
"id": [1, 2, 3],
"score": [1.0, 2.0, None],
"name": ["Ana", "Ben", None],
"active": [True, False, None],
})
print(df.dtypes)
converted = df.convert_dtypes()
print(converted.dtypes)
print(converted)Before the call, id is int64, score is float64, and name and active are object. After it, the dtypes are Int64, Int64, string and boolean. The missing value in score is now <NA>. The column keeps integer values instead of becoming floats.
The original df is unchanged. Assign the result back if you want to keep it.
What it does not do
convert_dtypes() does not parse text. A column of strings that look like numbers or dates is still text, so it becomes string, not a number.
import pandas as pd
raw = pd.DataFrame({"qty": ["3", "5", "7"]})
print(raw.convert_dtypes().dtypes) # qty is string, not Int64
raw["qty"] = pd.to_numeric(raw["qty"]).astype("Int64")
print(raw.dtypes)Currency symbols, thousands separators and date strings still need the cleaning and parsing steps from earlier chapters. A good order is to clean and parse first, then call convert_dtypes() to tidy the columns that are left.
Columns with mixed Python types, such as [1, "a"], stay object.
Controlling the conversion
Each rule has a switch. All default to True.
import pandas as pd
df = pd.DataFrame({
"n": [1, 2, 3],
"label": ["a", "b", "c"],
})
out = df.convert_dtypes(convert_integer=False, convert_string=False)
print(out.dtypes)The parameters are convert_string, convert_integer, convert_boolean and convert_floating. With convert_integer=False, whole-number floats stay Float64. infer_objects controls whether object columns are examined at all.
In pandas 2.x you can also pass dtype_backend="pyarrow" to get Arrow-backed dtypes instead of the NumPy-based nullable ones. This needs the pyarrow package installed.
Common mistakes
- Expecting parsing. If a column is still
stringafter the call, the values were text. Usepd.to_numericorpd.to_datetime. - Forgetting to assign.
df.convert_dtypes()on its own line changes nothing. - Surprise integer conversion. A float column such as ids
[1.0, 2.0, NaN]becomesInt64. This is usually what you want. If the values are measurements that happen to be whole, setconvert_integer=False. - Downstream code that expects NumPy dtypes. Some libraries do not accept
<NA>. Test your pipeline, or convert only the columns that need it.
Exercise
A DataFrame has a column "age" with the object values ["34", "29", "41"]. After df = df.convert_dtypes(), what is the dtype of "age", and what must you do to get an integer column?
Show answer
The dtype is string, because convertdtypes does not parse text. Convert it with df["age"] = pd.tonumeric(df["age"]).astype("Int64"), either before or after calling convert_dtypes.
Exercise
A column holds [1.0, 2.0, None] and you want it to stay a float column. How do you call convert_dtypes so it does not become Int64?
Show answer
Pass convertinteger=False, as in df.convertdtypes(convert_integer=False). The column then becomes Float64.