Sub topic 11
The default str dtype in pandas 3
This chapter assumes you know the string dtype, the .str accessor, and how pd.NA behaves in text columns. It also assumes you have seen the python and pyarrow storage backends from earlier chapters. It covers what changes in pandas 3, where the new dtype differs from string, and how to prepare existing code.
What changed in pandas 3
Before pandas 3, a column built from Python strings had dtype object. You had to opt in to a dedicated text type with dtype="string". In pandas 3, inference changed. Text data now gets a new dtype called str by default.
import pandas as pd
print(pd.__version__)
s = pd.Series(["apple", "banana", None])
print(s.dtype)
print(s.isna().tolist())On pandas 3 this prints str as the dtype, and the missing entry is still found by isna(). On pandas 2.x the same code prints object.
The change applies wherever pandas infers a dtype from text. That includes:
pd.Series([...])andpd.DataFrame({...})built from Python stringspd.read_csvand other readers, for text columnsastype(str), which now producesstrinstead ofobject- column labels, which can also use the string dtype
Data that mixes strings with other Python objects, such as ["a", 1], still gets object. The str dtype holds only strings and missing values.
str is not the same as string
The names are close and both are StringDtype underneath, but they behave differently. The difference that matters most is the missing-value marker.
| Property | `object` | `string` | `str` (pandas 3 default) |
|---|---|---|---|
| Alias | `"object"` | `"string"` | `"str"` |
| Missing marker | `None` or `NaN` | `pd.NA` | `np.nan` |
| Boolean results of `.str` predicates | `object` or `bool`, depends on data | nullable `boolean` | plain NumPy `bool` |
| Accepts non-string values | yes | no | no |
| Storage | Python objects | `python` or `pyarrow` | `pyarrow` if installed, otherwise `python` |
The str dtype keeps the NaN convention that people already used with object columns. It adds strict string typing and, when pyarrow is available, compact Arrow storage. The string dtype uses pd.NA and three-valued logic, which is a bigger change for existing code. The pandas developers chose the NaN variant as the default to break less code.
import pandas as pd
a = pd.Series(["x", None], dtype="str")
b = pd.Series(["x", None], dtype="string")
print(a.dtype, b.dtype)
print(a.iloc[1], b.iloc[1])
print((a == "x").dtype)
print((b == "x").dtype)The output shows str string, then nan <NA>, then bool, then boolean. Comparing a str column gives an ordinary NumPy boolean result, and a missing entry compares as False. Comparing a string column gives a nullable boolean result, and a missing entry stays <NA>.
Choosing the dtype explicitly
You can still choose any of the three representations. The dtype="str" alias gives the default behavior, and you can also build it from StringDtype:
import numpy as np
import pandas as pd
default_like = pd.Series(["a", None], dtype=pd.StringDtype(na_value=np.nan))
na_style = pd.Series(["a", None], dtype=pd.StringDtype())
print(default_like.dtype, default_like.iloc[1])
print(na_style.dtype, na_style.iloc[1])The na_value argument selects the missing-value convention. With np.nan you get the str dtype. With the default you get the string dtype and pd.NA. The storage argument still picks the backend, as in the earlier chapter on storage.
Use str when you want the default behavior and minimal code changes. Use string when you want pd.NA semantics, for example in a pipeline that already handles nullable integers and booleans the same way.
Strict typing
An object column accepts anything. A str column does not. Assigning a non-string value fails instead of silently turning the column back into object.
import pandas as pd
s = pd.Series(["a", "b"])
try:
s.iloc[0] = 1
except TypeError as err:
print("TypeError:", err)
s.iloc[0] = "z"
print(s.tolist())This catches a common bug, where a numeric value slips into a text column during cleaning. It also breaks code that used text columns as a general scratch space. If you assign counts, flags, or lists into a column that started as text, convert that column to object first, or better, put the values in a separate column.
Two related changes follow from this:
- Reductions and
.strmethods on astrcolumn never have to guess about element types, so the results are predictable. to_numpy()on astrcolumn still returns anobjectNumPy array, because NumPy has no equivalent dtype. Code that checksarr.dtype == objecton that result keeps working.
Missing values: what stays and what changes
The marker for missing text is NaN, so most object-era habits still work. isna(), fillna(""), dropna(), and s != s all behave as before.
The main difference from object is the dtype of results. Methods that return numbers, such as str.len(), return a numeric column. A missing entry becomes NaN, so the result is a float column when any value is missing. Predicates such as str.contains, str.startswith, and str.isdigit return a plain bool column, where a missing entry counts as False. Passing na=False explicitly, as in the filtering chapter, still works and makes the code clearer. It also keeps the same code correct if the column is later switched to string.
import pandas as pd
s = pd.Series(["alpha", None, "gamma"])
keep = s.str.contains("a", na=False, regex=False)
print(s[keep].tolist())This code gives the same filtered result on object, string, and str columns. Writing it this way is the cheapest way to make filtering code independent of the dtype.
Code that breaks on upgrade
Most .str code runs unchanged. The failures that do occur usually come from a few patterns.
- Selecting text columns with
object.df.select_dtypes(include="object")no longer finds text columns, because they are nowstr. Useinclude="str", or select with a function that tests the dtype. - Comparing dtypes to
object. Checks such asdf["name"].dtype == objectreturnFalsefor astrcolumn. Usepd.api.types.is_string_dtype(df["name"]), which acceptsobject,string, andstrcolumns that contain strings. - Writing non-strings into text columns. This now raises
TypeError, as shown above. - Expecting
pd.NA. If code testsx is pd.NAon text, it needspd.isna(x)instead. - Assuming
object-specific memory behavior. Memory use and speed change, usually for the better. Benchmarks you ran onobjectcolumns are out of date.
import pandas as pd
df = pd.DataFrame({"name": ["Ada", "Alan"], "age": [36, 41]})
text_cols = [c for c in df.columns if pd.api.types.is_string_dtype(df[c])]
print(text_cols)
print(df.select_dtypes(include="str").columns.tolist())The first line of output is ['name'], and so is the second. The first approach works on every pandas version. The second works when the str dtype is active.
Preparing code before you upgrade
You do not have to move to pandas 3 to test the new behavior. Recent pandas 2.x releases (2.3 and later) let you opt in to the new inference:
import pandas as pd
pd.options.future.infer_string = True
s = pd.Series(["a", "b"])
print(s.dtype)Set this option at the top of your test suite or a scratch script, run your tests, and fix the failures from the list above. On pandas 3 the option defaults to on, so the same code needs no change. The future option namespace is a transition tool, so avoid relying on it in long-lived production code.
A migration checklist:
- Pin or note your current pandas version, and install pyarrow in the test environment.
- Turn on
future.infer_stringand run the tests. - Replace
dtype == objectchecks andselect_dtypes(include="object")calls. - Add
na=Falseandregex=arguments to filtering calls, so they are explicit. - Find any place that stores non-strings in text columns and move them to
objector separate columns. - Re-check memory and timing. Compare against your earlier measurements, not against assumptions.
- Decide per column whether
str,string, orcategoryis right. The default does not makecategoryobsolete. A column with few distinct values still uses much less memory ascategory.
When pyarrow is missing
The str dtype is designed around pyarrow storage, but pyarrow is not strictly required. If pyarrow is not installed, pandas falls back to the python backend and keeps the same NaN semantics. Results are the same, so code stays portable. Performance and memory are closer to object, because the strings are Python objects again.
Check which backend you got:
import pandas as pd
s = pd.Series(["a", "b"])
print(s.dtype)
print(s.array.dtype.storage)The second line prints pyarrow or python. Test it in each deployment environment, since a slim container without pyarrow runs on the slower backend without warning.
Summary of decisions
- Leave new code on the default
strunless you have a reason not to. - Choose
stringif the rest of your data usespd.NAand you want one missing-value convention across all columns. - Choose
categoryfor text with few distinct, heavily repeated values. - Keep
objectfor mixed content only. - Write filters with
na=Falseand an explicitregex=argument, so they behave the same on all three dtypes.
Exercise
A script runs df.select_dtypes(include="object") to find text columns and then cleans each one. After upgrading to pandas 3, it silently cleans nothing. Why, and what two changes would fix it in a way that also works on older pandas versions?
Show answer
In pandas 3, text columns have dtype str, not object, so select_dtypes(include="object") no longer matches them. One fix is to select with pd.api.types.is_string_dtype(df[c]) in a list comprehension over the columns, which works on object, string, and str columns. The other is to pass include=["object", "str"] on pandas 3, or to guard the selection by version. Note that is_string_dtype on an object column checks the values, so it can be slower on very wide frames.
Exercise
You have a = pd.Series(["x", None], dtype="str") and b = pd.Series(["x", None], dtype="string"). What are the dtypes of a == "x" and b == "x", and what is the value at position 1 of each result?
Show answer
a == "x" has NumPy dtype bool, and position 1 is False. b == "x" has the nullable boolean dtype, and position 1 is <NA>, because comparing a missing value with "x" is unknown under pd.NA semantics.
Exercise
A cleaning step does df["code"].iloc[0] = 0 on a column of product codes stored as text. It worked on pandas 2.2 and raises TypeError on pandas 3. Explain why, and give a fix that keeps the column as text.
Show answer
The column is now str, which accepts only strings and missing values, while on pandas 2.2 it was object and accepted any value. Assign a string instead: df.loc[df.index[0], "code"] = "0". If the column really needs mixed values, convert it with astype(object) first, but mixed content in a code column is usually a sign of a data problem.