Sub topic 2
Meet the string dtype
This chapter introduces StringDtype, the dedicated text type in pandas. It assumes you know basic Python strings, how to create and index a Series or DataFrame, and what a dtype is. Later chapters cover missing values, the .str accessor, conversion strategies, and storage backends in depth. Here you will learn what the dtype is, how to create it, and which rules it enforces.
What the string dtype is
A pandas dtype describes what a column may hold and how operations on it behave. The object dtype is a catch-all. It stores references to arbitrary Python objects, so a column of text is just a column of objects that happen to be str.
The string dtype (class pandas.StringDtype) is a dedicated extension type for text. A column with this dtype holds only strings and missing values. Its missing-value marker is pd.NA.
A short comparison:
| Property | `object` column | `string` column |
|---|---|---|
| Allowed values | Anything | Strings and `pd.NA` |
| Missing marker | `NaN`, `None`, or both | `pd.NA` |
| Result of `==` | `bool` | nullable `boolean` |
| Result of `.str.len()` | `float64` if missing values exist | `Int64` |
| Can you tell it holds text from the dtype alone? | No | Yes |
The last row is the main point. With object, the dtype tells you nothing about the contents. With string, the dtype is a promise.
Seeing the difference
Start with a column built from Python strings and None.
import pandas as pd
s = pd.Series(["apple", "banana", None])
print(s.dtype)
t = s.astype("string")
print(t.dtype)
print(t.isna().tolist())On pandas 2.x the first line prints object and the second prints string. The missing entry is stored as pd.NA, and isna() reports [False, False, True].
On pandas 3 the first line prints str, because text is inferred as a new default string dtype. The str dtype is covered in a later chapter. This chapter uses the explicit "string" dtype, which behaves the same way in both versions.
An object column can also hold things that are not text, and nothing warns you:
import pandas as pd
o = pd.Series(["a", 1, None, 2.5], dtype="object")
print(o.map(type).tolist())This prints four different Python types: str, int, NoneType, and float. Code that assumes "this column is text" will fail on the second element, or worse, silently produce wrong output.
Ways to get a string column
There are several ways to create a column with the string dtype. All of them end up with the same result.
At construction
Pass dtype="string" to a Series or DataFrame constructor, or use the dtype object itself:
import pandas as pd
a = pd.Series(["x", "y", None], dtype="string")
b = pd.Series(["x", "y", None], dtype=pd.StringDtype())
c = pd.array(["x", "y", None], dtype="string")
print(a.dtype, b.dtype, c.dtype)
print(a.equals(b))The alias "string" is a plain string, so it is easy to type. The class pd.StringDtype() is what you use when you need to pass options such as the storage backend.
With astype
astype("string") converts an existing column. It works on non-text data too. Each value is converted to its string form, and missing values stay missing.
import pandas as pd
n = pd.Series([1, 2, None], dtype="Int64")
print(n.astype("string").tolist())This prints ['1', '2', <NA>]. Converting a numeric column to text is a one-way change. You can parse it back with pd.to_numeric, but formatting such as 1.0 versus 1 may have been lost along the way.
When reading files
Use the dtype argument of read_csv to get text columns without a conversion step. This also protects identifiers with leading zeros, which a numeric guess would damage.
from io import StringIO
import pandas as pd
csv = "name,code\nAda,001\nAlan,\n"
df = pd.read_csv(StringIO(csv), dtype={"name": "string", "code": "string"})
print(df)
print(df.dtypes)The code 001 keeps its zeros, and the empty field becomes <NA>. Without the dtype mapping, code would be read as a number and 001 would become 1.
With convert_dtypes
DataFrame.convert_dtypes() moves every column to the best-fitting nullable dtype. Text columns become string and integer columns become Int64. That method gets its own chapter, so only note here that it exists.
What the dtype enforces
The string dtype checks values when you assign them. An object column accepts anything:
import pandas as pd
o = pd.Series(["a", "b"], dtype="object")
o.iloc[0] = 1
print(o.tolist())
s = pd.Series(["a", "b"], dtype="string")
try:
s.iloc[0] = 1
except TypeError as exc:
print("TypeError:", exc)
s.iloc[0] = "z"
s.iloc[1] = pd.NA
print(s.tolist())The object column quietly becomes [1, 'b']. The string column raises a TypeError for the integer, and then accepts both a new string and pd.NA.
This is the practical benefit of the dtype. A bad value fails at the line that introduced it, not later in a different part of the program when something calls .str on a number.
Missing values in brief
The next chapter treats missing values in detail. Two behaviours matter now, because they show up as soon as you print a string column.
First, missing entries display as <NA>:
import pandas as pd
t = pd.Series(["apple", "banana", None], dtype="string")
print(t)The output is:
0 apple
1 banana
2 <NA>
dtype: stringSecond, comparisons return a nullable boolean column, not a plain bool one. The result for a missing entry is <NA>, not False:
import pandas as pd
t = pd.Series(["apple", "banana", None], dtype="string")
print(t == "apple")
o = pd.Series(["apple", "banana", None], dtype="object")
print(o == "apple")The string column gives True, False, <NA> with dtype boolean. The object column gives True, False, False with dtype bool. The object result cannot distinguish "not equal" from "unknown". The string result can.
This matters for filtering. A boolean mask that contains <NA> cannot be used directly to index in some situations, and it needs an explicit decision about what missing should mean. The chapters on missing values and the .str accessor show the usual answers, including fillna(False) and the na= argument of str.contains.
Two spellings to keep apart
Several names look alike. They refer to different things.
| Spelling | Meaning |
|---|---|
| `"string"` | The nullable string dtype with `pd.NA` as its missing value. |
| `pd.StringDtype()` | The same dtype as a class instance. Accepts a `storage` argument. |
| `"object"` | The generic Python-object dtype. |
| `str` (the Python type) | In `astype(str)` on pandas 2.x, converts to Python strings but keeps `object` dtype and turns missing values into the text `"nan"` or `"None"`. |
| `"str"` (pandas 3) | The new default string dtype. It uses `NaN` as its missing marker. |
The fourth row is a common source of bugs. Compare these on pandas 2.x:
import pandas as pd
s = pd.Series(["a", None])
print(s.astype(str).tolist())
print(s.astype("string").tolist())The first line prints ['a', 'None']. The missing value became a real string, and isna() would now say nothing is missing. The second prints ['a', <NA>]. Use "string" when you want to preserve missingness.
Storage backends
A string column can keep its data in two ways. The python backend stores Python string objects in a NumPy array, as object columns do. The pyarrow backend stores text in Apache Arrow's compact format, and it requires the pyarrow package. You choose a backend through the dtype:
import pandas as pd
print(repr(pd.StringDtype("python")))This prints string[python]. The alias "string[pyarrow]" selects the Arrow backend. Which backend plain "string" selects depends on your pandas version, your installed packages, and the mode.string_storage option. The choice affects memory and speed but not the values you see. A later chapter compares the two.
Common mistakes
- Assuming a string column holds only strings after
astype(str). That call yields anobjectcolumn, not thestringdtype. - Expecting
NaNin astringcolumn. Missing values arepd.NA. Checks likex != xornp.isnando not work on them. Useisna()andnotna(). - Forgetting to pass
dtypewhen reading identifiers. Zip codes, product codes, and phone numbers should be read asstring. Otherwise the parser may turn them into numbers. - Mixing up
"string"and"str". They are different dtypes in pandas 3, with different missing-value rules. - Testing dtype with
is. Usepd.api.types.is_string_dtype(col)or compare with==. Astringcolumn's dtype compares equal to"string", and itsdtype.storagetells you the backend.
Practice
Exercise
A Series is created with pd.Series(["a", None, "c"]) on pandas 2.x. You call s.astype(str) and then s.astype("string"). Which result still reports the middle entry as missing, and why?
Show answer
Only s.astype("string"). The astype(str) call turns None into the text "None" and keeps the object dtype, so isna() reports nothing missing. The "string" conversion keeps the entry as pd.NA, which isna() reports as missing.
Exercise
You have a string column s = pd.Series(["a", "b"], dtype="string"). What happens when you run s.iloc[0] = 5, and what would happen on an object column?
Show answer
On the string column, pandas raises a TypeError because 5 is not a string or pd.NA. On an object column the assignment succeeds and the column silently holds a mixed int and str.
Exercise
Write a read_csv call that reads a column named "zip" so that the value 02134 keeps its leading zero and empty fields become pd.NA.
Show answer
pd.read_csv(path, dtype={"zip": "string"}). The string dtype keeps the text as read, so 02134 stays "02134", and empty fields become pd.NA.