Sub topic 11
The default str dtype in pandas 3
This chapter assumes you know what a dtype is, can build a Series or DataFrame, and have met the string dtype and the .str accessor from earlier chapters. It covers what changes in pandas 3 and how to prepare existing code.
What changed
Before pandas 3, a column of Python strings had dtype object. In pandas 3, pandas infers a dedicated dtype named str for text. You get it without asking for it:
import pandas as pd
s = pd.Series(["apple", "banana", None])
print(s.dtype)
print(s.isna().tolist())
print(s[2])On pandas 3 this prints str, then [False, False, True], then nan. In pandas 2.3 you can try the new behavior first with pd.options.future.infer_string = True.
The inference applies wherever pandas builds a column from Python strings. That covers constructors, read_csv, and other readers. A column that mixes strings with other objects, such as ["a", 1], stays object.
str is not the same as string
The names are close, but the two dtypes treat missing values differently.
| Aspect | `"string"` | `"str"` (pandas 3 default) |
|---|---|---|
| Missing value | `pd.NA` | `np.nan` |
| Integer results of `.str` methods | `Int64` | `float64` with `NaN` |
| Boolean results of `.str` methods | nullable `boolean` | NumPy `bool` |
| How you get it | `dtype="string"` | Inferred, or `dtype="str"` |
The str dtype keeps the missing-value convention that object columns used. That makes upgrades less disruptive. It still gives you strict typing and faster storage.
import pandas as pd
a = pd.Series(["x", None, "abc"], dtype="str")
b = pd.Series(["x", None, "abc"], dtype="string")
print(a.str.len())
print(b.str.len())a.str.len() returns float64 with NaN. b.str.len() returns Int64 with <NA>.
Strictness
A str column accepts only strings and missing values. Assigning anything else raises an error instead of quietly turning the column into object:
import pandas as pd
s = pd.Series(["a", "b"])
try:
s[0] = 1
except TypeError as err:
print("TypeError:", err)This catches bugs early. If you really want mixed contents, convert explicitly with s.astype(object).
Storage
The default str dtype uses PyArrow storage when pyarrow is installed. Otherwise it falls back to Python objects, with the same behavior but less speed and memory benefit. You can request a backend explicitly:
import numpy as np
import pandas as pd
dtype = pd.StringDtype("python", na_value=np.nan)
s = pd.Series(["a", "b"], dtype=dtype)
print(s.dtype)Most code should leave the choice to pandas.
Preparing existing code
These patterns commonly break or change behavior:
- Checks like
df[col].dtype == object. They are nowFalsefor text. Usepd.api.types.is_string_dtype(df[col]). select_dtypes(include="object"). It no longer returns text columns. Useinclude=["object", "str"].- Assigning non-strings into text columns. Convert the values first, or cast the column to
object. - Code that relies on
pd.NA. If you useddtype="string"deliberately, nothing changes for those columns. Do not mix up the two missing-value conventions in one pipeline. - Code that expects object arrays.
s.to_numpy()on astrcolumn may not give the NumPy array type you assumed. Check any code that handles raw arrays.
Checklist
- Let pandas infer
strfor ordinary text columns. - Use
dtype="string"only when you wantpd.NAsemantics. - Use
categoryfor text with few distinct values. - Replace
== objectchecks andselect_dtypes("object")calls.
Exercise
In pandas 3, you run df.select_dtypes(include="object") on a DataFrame with a column of names read from a CSV file, and the names column is missing from the result. Why, and how do you fix the call?
Show answer
The names column has the inferred str dtype, not object, so the selection skips it. Use df.select_dtypes(include=["object", "str"]), or test columns with pd.api.types.is_string_dtype.
Exercise
A str column holds ["a", None, "abc"]. What dtype does .str.len() return, and what dtype would you get from a column with dtype="string"?
Show answer
The str column returns float64 with NaN for the missing entry, because its missing value is np.nan. The string column returns Int64 with <NA>.