Sub topic 2
Meet the string dtype
What you should already know
This chapter assumes you can build a Series or DataFrame and know what a dtype is. It also assumes you know basic Python strings. The previous chapter showed why object columns are an unreliable home for text. Here you meet the replacement.
What the string dtype is
The string dtype (class pd.StringDtype) is a pandas extension type built only for text. An object column can hold any Python value, such as a string, an integer, a list, or None. A string column holds only text and a single missing-value marker, pd.NA.
That restriction is useful. With string, s.dtype tells you the column holds text. With object, the dtype tells you nothing about what is inside.
Creating a string column
You can request the dtype when you build the data, or convert later with astype. Pass the lowercase alias "string" in both cases.
import pandas as pd
s = pd.Series(["apple", "banana", None])
print(s.dtype)
t = s.astype("string")
print(t.dtype)
print(t.isna().tolist())This prints:
object
string
[False, False, True]The first Series has dtype object because pandas could not know you meant text. After astype("string"), the dtype is string. The None is stored as pd.NA, and isna() finds it.
To skip the conversion step, pass the dtype at construction:
import pandas as pd
s = pd.Series(["apple", "banana", None], dtype="string")
print(s)The output shows <NA> for the missing entry, not None or NaN.
The conversion path
The diagram shows what changes during conversion.
What changes and what stays the same
Most of your text code keeps working. The .str accessor, indexing, comparison, and sort_values all behave as before. The differences appear in three places.
| Aspect | `object` column | `string` column |
|---|---|---|
| Allowed contents | Any Python value | Text and `pd.NA` only |
| Missing marker | `None` or `NaN`, often mixed | `pd.NA` |
| `dtype` reports | `object` | `string` |
| Comparison results | `False` for a missing entry | `<NA>` for a missing entry |
| Boolean results from `.str` | `object` when missing values are present | Nullable `boolean` |
The last two rows matter most in practice. A comparison against a missing entry in a string column returns <NA>, not False. Filtering with that result needs extra care, which the next chapters cover.
Checking what you have
Check a column's dtype before you choose a method for it. These checks are reliable:
import pandas as pd
s = pd.Series(["a", "b"], dtype="string")
print(s.dtype)
print(pd.api.types.is_string_dtype(s))
print(isinstance(s.dtype, pd.StringDtype))is_string_dtype is also true for some object columns that contain only strings, so it is less strict. Use the isinstance check when you need to know that a column is exactly the string dtype.
Common mistakes at this stage
- Assuming
astype("string")cleans the data. It converts the container. It does not strip whitespace or fix casing. - Expecting
NaNto stayNaN. Missing entries becomepd.NAafter conversion. Code that testsx is np.nanwill no longer match. - Writing
dtype=stringwithout quotes. That is aNameError, becausestringis not a Python name here. Use"string"orpd.StringDtype().
Exercise
You run s = pd.Series(["x", None, "z"]).astype("string"). What is s.dtype, and what does s.isna().tolist() return?
Show answer
s.dtype is string. s.isna().tolist() returns [False, True, False], because the None in the middle is stored as pd.NA, and isna() marks it as missing.
Exercise
Why would you choose dtype="string" over object for a column of customer names?
Show answer
The string dtype guarantees the column holds only text and pd.NA. The dtype then describes the contents, missing values use one marker, and .str results use nullable types. An object column can hide mixed types and mixed missing markers.